LoginSignup
64
60

More than 5 years have passed since last update.

C# : Visual Studio で気軽に前回値の保存と復元を行う方法

Posted at

■目的

フォーム内で入力した値を保存して、再起動したときに値を復元させたい

■準備

適当なフォームを作ります(プロジェクト名:Hoge、フォーム名:Form1)

image

保存させるコントロール

  • txtHogeString という名前のTextBox(上段)
  • txtHogeInt という名前のTextBox(下段)

■入力した値を保存する変数を定義

ソリューションエクスプローラー > Hogeのプロパティ > 設定

名前 スコープ
HozonString string ユーザー
HozonInt int ユーザー 0

image

■クローズイベント(保存処理)の作成

Hoge.Form1.cs
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    Properties.Settings.Default.HozonString = this.txtHogeString.Text;
    Properties.Settings.Default.HozonInt = int.Parse(this.txtHogeInt.Text);
    Properties.Settings.Default.Save();
}

■ロードイベント(復元処理)の作成

Hoge.Form1.cs
private void Form1_Load(object sender, EventArgs e)
{
    this.txtHogeString.Text = Properties.Settings.Default.HozonString;
    this.txtHogeInt.Text = Properties.Settings.Default.HozonInt.ToString();
}

■完成

実行 > 適当な値を入力 > 閉じる > 実行 = (ヽ´ω`)

image

値はデフォならこの辺に保存されている↓

C:\Users\{User名}\AppData\Local\Hoge\...\1.0.0.0\user.config

■コード全体

Hoge.Form1.cs
using System;
using System.Windows.Forms;

namespace Hoge
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.txtHogeString.Text = Properties.Settings.Default.HozonString;
            this.txtHogeInt.Text = Properties.Settings.Default.HozonInt.ToString();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Properties.Settings.Default.HozonString = this.txtHogeString.Text;
            Properties.Settings.Default.HozonInt = int.Parse(this.txtHogeInt.Text);
            Properties.Settings.Default.Save();
        }
    }
}
64
60
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
64
60