/*******************************************/
/*★ ラジオボタンをグループ化 前田 稔 ★*/
/*******************************************/
using System;
using System.Drawing;
using System.Windows.Forms;
public class MyForm : Form
{
Label label;
RadioButton[] radioButton1 = new RadioButton[4];
RadioButton[] radioButton2 = new RadioButton[3];
GroupBox groupBox1; // グループボックス1
GroupBox groupBox2; // グループボックス2
string color;
string flower;
public MyForm()
{
label = new Label();
label.AutoSize = true;
label.Location = new Point(20, 240);
string[] item1 = { "チューリップ", "コスモス", "シクラメン", "ゆり" };
for (int i = 0; i < 4; i++)
{
radioButton1[i] = new RadioButton();
radioButton1[i].Text = item1[i];
radioButton1[i].Left = 10;
radioButton1[i].Top = i * 22 + 20;
radioButton1[i].CheckedChanged +=
new EventHandler(radioButton_CheckedChanged1);
}
radioButton1[0].Checked = true; // 最初は 'チューリップ' を選択
string[] item2 = { "赤", "白", "黄" };
for (int i = 0; i < 3; i++)
{
radioButton2[i] = new RadioButton();
radioButton2[i].Text = item2[i];
radioButton2[i].Left = 10;
radioButton2[i].Top = i * 22 + 20;
radioButton2[i].CheckedChanged +=
new EventHandler(radioButton_CheckedChanged2);
}
radioButton2[0].Checked = true; // 最初は '赤' を選択
groupBox1 = new GroupBox();
groupBox1.Text = "花";
groupBox1.Location = new Point(20, 10);
groupBox1.Size = new Size(160, 120);
groupBox1.Controls.AddRange(radioButton1);
groupBox2 = new GroupBox();
groupBox2.Text = "色";
groupBox2.Location = new Point(20, 140);
groupBox2.Size = new Size(160, 90);
groupBox2.Controls.AddRange(radioButton2);
this.Controls.Add(label);
this.Controls.Add(groupBox1);
this.Controls.Add(groupBox2);
}
// 花が変更されたときのイベントハンドラ
void radioButton_CheckedChanged1(object sender, EventArgs e)
{
RadioButton radioButton = sender as RadioButton;
if (radioButton.Checked)
{
flower = radioButton.Text;
label.Text = string.Format("花:" + flower + " 色:" + color);
}
}
// 色が変更されたときのイベントハンドラ
void radioButton_CheckedChanged2(object sender, EventArgs e)
{
RadioButton radioButton = sender as RadioButton;
if (radioButton.Checked)
{
color = radioButton.Text;
label.Text = string.Format("花:" + flower + " 色:" + color);
}
}
}
class form01
{
public static void Main()
{
MyForm mf = new MyForm();
Application.Run(mf);
}
}
|