วันพฤหัสบดีที่ ๑๒ มิถุนายน พ.ศ. ๒๕๕๑

จัดการกับ radioButton หลายๆอัน

ถ้าใช้ radioButton หลายๆอันในฟอร์ม

เบื่อไหมครับที่จะต้องเขียนโค้ด เช่น
if(radioButton1.Checked)
.....
else if(radioButton2.Checked)

.....

ลองใช้วิธีนี้ไหมครับ
ให้คลิกที่ radioButton อันแรก จากนั้นกดแป้น Ctrl ค้างไว้แล้วคลิก radioButton ที่เหลือ
จากนั้นก็เลือก Event ชื่อ CheckedChanged แล้วพิมพ์ชื่อ radioChange แล้วกดแป้น Enter

ที่เหลือก็แก้ไขรหัสโปรแกรมดังนี้ครับ

string sradio;

public Form1()
{
InitializeComponent();
}

private void radioChange(object sender, EventArgs e)
{
//cast sender object to radiobutton
RadioButton radioFood = (RadioButton)sender;
if (radioFood.Checked)
sradio = radioFood.Text;

}

private void bttOK_Click(object sender, EventArgs e)
{
MessageBox.Show("คุณเลือก "+sradio,"รายการที่คุณเลือก",MessageBoxButtons.OK, MessageBoxIcon.Information);
}