C#でラジオボタンを設定に記録する方法

このQ&Aのポイント
  • C#でグループボックスに並んでいるラジオボタンのチェック状態を保存して復元する方法を教えてください。
  • Properties.Settings.Defaultを使用して、ラジオボタンのチェック状態を保存しましょう。
  • セットアップしたラジオボタンのチェック状態を保存し、プログラム再起動時に復元できます。
回答を見る
  • ベストアンサー

C#でラジオボタンを設定に記録する方法

すみません、どなたかご存知のかた教えてください。 C#でグループボックスの上に20個くらいのラジオボタンが並んでいて、どれかをチェックした時設定として保存し、プログラムを再起動した時チェック状態を復元したいのですが、どのようにすれば良いでしょうか? Properties.Settings.Defaultで型をSystem.Windows.Forms.RadioButtonにして(RadioButton)senderを記憶するようにしてみましたが(プログラムが分かって無いからですが)だめでした。 現在はProperties.Settings.Defaultの型をstringにして、次のような形で動かしていますが、なんとかシンプル(スマート)にしたいのです。 private void Form1_Load(object sender, EventArgs e) { switch (Properties.Settings.Default.SelectedProgram) { case "Func1": radioButtonFunc1.Checked = true; break; case "Func2": radioButtonFunc2.Checked = true; break; case "Func3": radioButtonFunc3.Checked = true; break; default: break; } } //各ラジオボタン共通 private void radioButtonSelect_Click(object sender, EventArgs e) { string RadioButtonText = null; RadioButton _RadioButton = (RadioButton)sender; if (_RadioButton.Checked == true) { RadioButtonText = _RadioButton.Text; Properties.Settings.Default.SelectedProgram = RadioButtonText; switch (RadioButtonText) { case "Func1": textBox1.Text = "a"; break; case "Func2": textBox1.Text = "b"; break; case "Func3": textBox1.Text = "c"; break; default: break; } } } //プログラム開始ボタン private void buttonStart_Click(object sender, EventArgs e) { string RadioButtonText = null; foreach (RadioButton prgText in groupBox1.Controls) { if (prgText.Checked) { RadioButtonText = prgText.Text; break; } } switch (RadioButtonText) { case "Func1": Func1(); break; case "Func2": Func2(); break; case "Func3": Func3(); break; default: break; } } private void Func1() { } private void Func2() { } private void Func3() { }

noname#207939
noname#207939

質問者が選んだベストアンサー

  • ベストアンサー
回答No.2

>textBox1.Text = prgText[current.Text]; >で「指定されたキーはディレクトリ内に存在しませんでした。」と表示されて止まってしまいます(なぜでしょう?)。 質問に掲載されていたプログラムが switch (RadioButtonText) { case "Func1": Func1(); break; case "Func2": Func2(); break; case "Func3": Func3(); break; default: break; のようになっていたので、ラジオボタンのテキストが "Func1"、"Func2"、"Func3" になっていると仮定して prgText.Add("Func1", "a"); prgText.Add("Func2", "b"); prgText.Add("Func3", "c"); としたのですが、ラジオボタンのテキストがこのいずれにも一致していないのではないでしょうか。 ちなみに、Dictionary の使用例として、一つ ( prgText ) はキーを String とし、もう一つの方 ( func ) はキーを RadioButton にしましたが、 private Dictionary<String, FuncDelegate> func; のようにすることもできますし、 private Dictionary<RadioButton, String> prgText; のようにすることもできます。 ( xxx = new Dictionary<...>(); 、XXX.Add(...); のところも合わせる必要あり )

noname#207939
質問者

お礼

見落としていました、たいへんお手数をおかけしてすみませんでした。 Dictionaryの使い方についても親切に説明していただき、たいへん助かりました、いろいろ応用してみます。 ありがとうございました!

その他の回答 (1)

回答No.1

設定の保存と復元については、RadioButton の Name を使用すると簡単になると思います。 保存の時 private void Form1_FormClosed(object sender, FormClosedEventArgs e) { foreach( RadioButton rb in groupBox1.Controls ) { if( rb.Checked ) { Properties.Settings.Default.RadioButtonName = rb.Name; Properties.Settings.Default.Save(); break; } } } のようにすると、復元時は string radioButtonName = Properties.Settings.Default.RadioButtonName; RadioButton rb = (RadioButton)groupBox1.Controls[radioButtonName]; if( rb != null ) { rb.Checked = true; } のようにできます。 ラジオボタンクリック時の処理に Dictionary を、プログラム開始ボタンクリック時の処理に Dictionary と delegate を使った例を載せておきます。 using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { delegate void FuncDelegate(); private RadioButton current; private Dictionary<string, string> prgText; private Dictionary<RadioButton, FuncDelegate> func; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { prgText = new Dictionary<string, string>(); prgText.Add("Func1", "a"); prgText.Add("Func2", "b"); prgText.Add("Func3", "c"); func = new Dictionary<RadioButton, FuncDelegate>(); func.Add(radioButtonFunc1, new FuncDelegate(Func1)); func.Add(radioButtonFunc2, new FuncDelegate(Func2)); func.Add(radioButtonFunc3, new FuncDelegate(Func3)); string radioButtonName = Properties.Settings.Default.RadioButtonName; current = (RadioButton)groupBox1.Controls[radioButtonName]; if (current != null) { current.Checked = true; textBox1.Text = prgText[current.Text]; } } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { foreach( RadioButton rb in groupBox1.Controls ) { if( rb.Checked ) { Properties.Settings.Default.RadioButtonName = rb.Name; Properties.Settings.Default.Save(); break; } } } private void radioButtonSelect_Click(object sender, EventArgs e) { current = (RadioButton)sender; textBox1.Text = prgText[current.Text]; } private void buttonStart_Click(object sender, EventArgs e) { func[current](); } private void Func1() { MessageBox.Show("Func1"); } private void Func2() { MessageBox.Show("Func2"); } private void Func3() { MessageBox.Show("Func3"); } } }

noname#207939
質問者

お礼

ご回答ありがとうございました! おかげさまで設定の復元もdelegateによる起動もうまくいきました。

noname#207939
質問者

補足

ご回答ありがとうございました! おかげさまで設定の復元もdelegateによる起動もうまくいきました。 解決はしたのですが、1点だけ補足(?)させてください。 42行目と63行目付近にある textBox1.Text = prgText[current.Text]; で「指定されたキーはディレクトリ内に存在しませんでした。」と表示されて止まってしまいます(なぜでしょう?)。 これらをコメントアウトすると、正しく動作します。 ちなみに操作したのは次の通りです。 新規にForm1を開き groupBox1, radioButtonFunc1, radioButtonFunc2, radioButtonFunc3 buttonStart textBox1 を配置 Settings.settingsにRadioButtonName(string)を登録 Form1のFormClosedにForm1_FormClosedを設定 各ラジオボタンにradioButtonSelect_Clickを設定 buttonStartのClickにradioButtonSelect_Clickを設定

関連するQ&A

  • Visual C++ 2008 EEでボタンの判定、結果を配列に格納

    OSはXPでViaual C++ 2008 Express EditionのWindowsフォームアプリケーションにて一つのフォームで全132問に答えるというものを作成しています。フォームには[戻る]、[次へ進む]、[チェック除外]ボタンと「はい」、「いいえ」、「どちらでもない」のラジオボタン、問題文とタイマーのラベル、テキストボックス(問題番号を入力すると[戻る]ボタンが[移動]ボタンに変わり、入力した問題に進む)があります。最初に変数qに1を入れ、[次へ進む]を押すとqに1がプラスされswitch文で2問以降に進む(ラベルのみ切り替わる)というもので、最後の問題に行くと[次へ進む]ボタンが[終了]ボタンに変わります。ただし、全ての問題に解答していなければ終了できないようにしています。この解答結果をCSVに(はいなら1、いいえなら2、どちらでもないなら3)出力したいと考えているのですが、ラジオボタンにチェックを入れ、[次へ進む]ボタンを押したときのみ「インデックスが配列の境界外です」というエラーが表示されてしまいます。コードは以下の通りですが、どこを直せばよいのか分からないのでご教授願います。 private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { endflag = 0; this->button2->Text = "次へ進む"; if(flag == 1){ q = jump; flag = 0; this->button1->Text = "戻る"; this->textBox1->Text = ""; }else{ q--; } if(q == 1){ this->button1->Enabled = false; } switch(q){ case 1:                          ・                          ・                          ・                          case 132                           endflag = 1; break; }                            }: private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) { String^ s = rtrstrg(); if(endflag == 1){ if(s == "") { MessageBox::Show("全ての質問に答えて下さい。","エラー"); } else if(MessageBox::Show("終了しますか?", "確認", MessageBoxButtons::OKCancel, MessageBoxIcon::Question) == System::Windows::Forms::DialogResult::OK) { this->Close(); } } q++; this->button1->Enabled = true; switch(q){ case 2:                      ・                      ・                      ・                      case 132                       endflag = 1;    break; }                      }: private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) { this->radioButton1->Checked = false; this->radioButton2->Checked = false; this->radioButton3->Checked = false; } private: System::Void chg(System::Object^ sender, System::EventArgs^ e) { bool result = int::TryParse(textBox1->Text, jump); if(jump > 0 && jump <= 132){ if(jump != q){ this->button1->Text = "移動"; this->button1->Enabled = true; flag = 1; } } else{ textBox1->Text = ""; this->button1->Text = "戻る"; flag = 0; } } private: System::String^ rtrstrg() { String^ s; for(int i=1; i<=QSTNB; i++) { s += this->rtrdt(i); if(s->EndsWith("×")) { return ""; } } return s->Remove(s->Length - 1); } private: System::String^ rtrdt(int qstn) { //配列の宣言 array<RadioButton^>^ arb = gcnew array<RadioButton^>(SZBH); for(int i=0; i<SZBH; i++) { arb[i] = dynamic_cast<RadioButton^>(this->Controls->Find("radioButton"+(qstn*SZBH-SZBH+1+i), true)[0]); } return this->chck(arb); } private: System::String^ chck(array<RadioButton^>^ arb) { for(int i=0; i<arb->Length; i++) { if(arb[i]->Checked == true) { return i + 1 + ","; } } return "×"; }

  • ラジオボタンのチェック

    Visual Basic 2010 Express windows7 Pro dmyが何であるかでラジオボタンのチェックを入れたいのですが、 下記の場合はそれぞれの値でチェックが入りません。 dmy = My.Computer.FileSystem.ReadAllText("dmy.txt") Select Case dmy Case "aaa" RadioButton4.Checked = True Case "bbb" RadioButton6.Checked = True Case "ccc" RadioButton7.Checked = True End Select 下記の場合、CheckBox7にチェックが入ると、 RadioButton1はオフになったので、 Trueにするだけで出来ると思ったのですが、変わりませんでした。 If CheckBox7.Checked Then RadioButton1.Checked = False End If

  • C#について・・・

    次のようなブログラムなのですが、ラジオボタンが上手く切り替わりません。 どこを修正すると上手くいくでしょうか? <<文字数オーバーのため省略>> public Form1() { // // Windows フォーム デザイナ サポートに必要です。 // InitializeComponent(); if(isJapanStyle) { label5.Text=string.Format("0時0分0秒"); label6.Text=string.Format("0時0分0秒"); } else { label5.Text=string.Format("00:00:00"); label6.Text=string.Format("00:00:00"); } // // TODO: InitializeComponent 呼び出しの後に、コンストラクタ コードを追加してください。 // <<文字数オーバーのため 省略>> static void Main() { Application.Run(new Form1()); } protected void button1_Click(object sender, System.EventArgs e) { if(isJapanStyle) { label5.Text=string.Format("{0}時{1}分{2}秒",dt.Hour,dt.Minute,dt.Second); } else { label5.Text=DateTime.Now.ToString("T"); } recTime=dt; timer2.Stop(); timer3.Start(); } private void button2_Click(object sender, System.EventArgs e) { Application.Exit(); } private void timer1_Tick(object sender, System.EventArgs e) { dt=DateTime.Now; if(isJapanStyle) { label4.Text=string.Format("{0}時{1}分{2}秒",dt.Hour,dt.Minute,dt.Second); } else { label4.Text=DateTime.Now.ToString("T"); } } private void timer3_Tick(object sender, System.EventArgs e) { keika=dt-recTime; if(isJapanStyle) { label6.Text=string.Format("{0}時間{1}分{2}秒",keika.Hours,keika.Minutes,keika.Seconds); } else { label6.Text=string.Format("{0}:{1}:{2}",keika.Hours,keika.Minutes,keika.Seconds); } } private void timer2_Tick(object sender, System.EventArgs e) { timer3.Stop(); } private void radioButton2_CheckedChanged(object sender, System.EventArgs e) { isJapanStyle=false; } private void radioButton1_CheckedChanged(object sender, System.EventArgs e) { isJapanStyle=true; } } }

  • C#でテキストボックスをクリック→フォームが開く→フォームで設定した値

    C#でテキストボックスをクリック→フォームが開く→フォームで設定した値を元のテキストボックスに入力 こんな感じのことをC#でやりたいのですがよくわからないので教えてください。 1. 親をForm1、子をForm2とします 2. Form1のTextBox1をクリックするとForm2が開いきます 3. Form2で設定した値をForm2の「入力」ボタンを押すとForm2が閉じてTextBox1に値が入力されます というものです。 ここで、textBoxは「クリックしたコントロール名を取得してForm2に渡したい」のです。 テキストボックスがたくさんあるので、textBox1とか決まった名前ではありません。 この部分がわからないのです。 ------------------------------------------------------- Form1: private void textBox1_Click(object sender, EventArgs e) {  Form2 fromItem = new Form2(sender);  DialogResult deRet = fromItem.ShowDialog(); } Form2: public Form2(object sender) {  InitializeComponent();  object pSender = sender; } private void button_input_Click(object sender, EventArgs e) {  ((System.Windows.Forms.TextBox)pSender).text = "hoge"; } ------------------------------------------------------- この程度しかわかりません。 正しい方法を教えてください。よろしくお願いいたします。

  • c# イベントハンドラ 統一

    trackBarを複数配置しているのですが、そのtrackBarごとに private void trackBar1_Scroll(object sender, EventArgs e) { previewcolor(this.trackBar1.Value,'赤'); } private void trackBar2_Scroll(object sender, EventArgs e) { previewcolor(this.trackBar1.Value, '青'); } private void trackBar3_Scroll(object sender, EventArgs e) { previewcolor(this.trackBar1.Value, '緑'); } private void trackBar4_Scroll(object sender, EventArgs e) { previewcolor(this.trackBar1.Value, '透'); } こんな風に別々に記述する形になって非常にスッキリしないです。 これをジェネリクス?やデリゲート?などを使ってすっきりできないのでしょうか? visual stdio c# 2008を使ってます。 宜しくお願いします。

  • VB2008EEのラジオボタンのチェック無し

    VB2008EEのラジオボタンのチェック無し     4つにチェックを入れてしまうと、全ての変数に値が入ってしまい、ボタンクリック時にチェックが 入っていないのを含めて、batファイル4つとも実行されてしまいます。 チェックボックスだと、下記でチェックされていないもの値を変えられます。 If CheckBox1.CheckState = CheckState.Unchecked Then   aaa = "9" End If ラジオボタンでチェックされていない所の変数を変える事は出来るでしょうか? Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If (aaa = "1") Then Shell("cmd /c xxx.bat", AppWinStyle.NormalFocus, True) End If If (bbb = "2") Then Shell("cmd /c yyy.bat", AppWinStyle.NormalFocus, True) End If If (ccc = "3") Then Shell("cmd /c zzz.bat", AppWinStyle.NormalFocus, True) End If If (ddd = "4") Then Shell("cmd /c www.bat", AppWinStyle.NormalFocus, True) End If End Sub Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged aaa = "1" End Sub Private Sub RadioButton2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton2.CheckedChanged bbb = "2" End Sub Private Sub RadioButton3_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton3.CheckedChanged ccc = "3" End Sub Private Sub RadioButton4_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton4.CheckedChanged ddd = "4" End Sub

  • Form2のテキストボックスを更新する方法(C#)

    namespace WindowsFormsApplication_test { public partial class Form1:Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender,EventArgs e) { Form2 Fm2 = new Form2(); Fm2.StartPosition = FormStartPosition.CenterScreen; Fm2.Show(); } private void button1_Click(object sender,EventArgs e) { Random a = new Random(); int x=a.Next(100); x=x+10; textBox1.Text=x+""; } } } 起動時にForm1とForm2を表示するプログラムを作ったのですが、 Form1のボタンをクリックした時、 Form2のtextBox1に、Form1のxの値を表示する方法が分かりません。 記述方法を教えて下さい。

  • C#でオブジェクトの有無を取得する

    オブジェクトが作られている時と作られていない時で処理をわけたいのですがうまくいきません。 この書き方の何がまずいのでしょうか? namespace オブジェクト検索 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Control c = Controls["form2"]; if (c != null) { ((TextBox)c).Text += "*"; } } private void button2_Click(object sender, EventArgs e) { Form2 form2 = new Form2(); form2.Show(); Application.DoEvents(); } } } ボタン2を押した時に新しいフォームが立ち上がり、そのフォームがあるときは*が出るようにしたいです。

  • C# 簡単なシューティング 自機移動について

    かなりの初心者で困っています。 簡単なシューティングを作ろうとおもっています。 使用ソフトはVisualC#2005です。 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //自機(右移動) private void button3_Click(object sender, EventArgs e) { if (timer1.Enabled == false) { timer2.Enabled = false; timer1.Enabled = true; } else { timer1.Enabled = false; timer3.Enabled = false; timer4.Enabled = false; } } private void timer1_Tick(object sender, EventArgs e) { pictureBox1.Left = pictureBox1.Left + 2; } //自機(左) private void button4_Click(object sender, EventArgs e) { if (timer2.Enabled == false) { timer1.Enabled = false; timer2.Enabled = true; } else { timer2.Enabled = false; timer3.Enabled = false; timer4.Enabled = false; } } private void timer2_Tick(object sender, EventArgs e) { pictureBox1.Left = pictureBox1.Left - 2; } //自機(上) private void button1_Click(object sender, EventArgs e) { if (timer3.Enabled == false) { timer4.Enabled = false; timer3.Enabled = true; } else { timer1.Enabled = false; timer2.Enabled = false; timer3.Enabled = false; } } private void timer3_Tick(object sender, EventArgs e) { pictureBox1.Top = pictureBox1.Top - 2; } //自機(下) private void button2_Click(object sender, EventArgs e) { if (timer4.Enabled == false) { timer3.Enabled = false; timer4.Enabled = true; } else { timer1.Enabled = false; timer2.Enabled = false; timer4.Enabled = false; } } private void timer4_Tick(object sender, EventArgs e) { pictureBox1.Top = pictureBox1.Top + 2; } } } 自機は画像(PictureBox)でボタンによって上下左右に移動します。 FormのSizeは800,630です。 自機の移動がボタンなのでキー入力によって操作できるようにしたいのですが、 それと、自機の移動範囲を画面からでないようにしたいです。 あまりC#を理解できてない上でつくったのでおかしな点が多々あると思います。 教えていただける方がいると助かります。

  • 【C#】EventArgsについて

    いつもお世話になります。 C#に関して質問です。 VisualC#2008を使っています。 private void Form1_Load(object sender, EventArgs e) などで見かける、EventArgs e とは何を意味しているのでしょうか? 誰か教えていただけませんか? よろしくお願いします。

専門家に質問してみよう