I have the following code which checks each radio button (Temp30, Temp40 and Temp60) and does the necessary things such as turning the wash temperature light on etc...

I want to create an event which handles all 3 radio buttons. I thought it could possibly have something to do with the groupbox they are in? (it is called TempGroupBox)

Any help would be much appreciated!

private void Temp30_CheckedChanged(object sender, EventArgs e)
{
    if (Temp30.Checked)
    {
        MainDisplayLabel.Text = ("   SELECT SPIN SPEED");
        WashTempLight.Visible = true;
        WashTempLight.Image = Properties.Resources._30degrees;
        SpeedGroupBox.Enabled = true;
    }
}

private void Temp40_CheckedChanged(object sender, EventArgs e)
{
    if (Temp40.Checked)
    {
        MainDisplayLabel.Text = ("   SELECT SPIN SPEED");
        WashTempLight.Visible = true;
        WashTempLight.Image = Properties.Resources._40degrees;
        SpeedGroupBox.Enabled = true;
    }
}

private void Temp60_CheckedChanged(object sender, EventArgs e)
{
    if (Temp60.Checked)
    {
        MainDisplayLabel.Text = ("   SELECT SPIN SPEED");
        WashTempLight.Visible = true;
        WashTempLight.Image = Properties.Resources._60degrees;
        SpeedGroupBox.Enabled = true;
    }
}
有帮助吗?

解决方案

You can bind all radioButton's event to the same handler and use sender parameter to get the control that the action is for.

private void Temps_CheckedChanged(object sender, EventArgs e)
{
    string checkedName = ((RadioButton)sender).Name;

    if(checkedName == "Temp40")
    {
        ...
    }
    else if(checkedName == "Temp60")
    {
        ...
    }
}

You can add event handler for all RadioBUttons's like that after InitializeComponent():

var radioButtons =this.Controls.OfType<RadioButton>();

foreach (RadioButton item in radioButtons)
{
      item.CheckedChanged += Temps_CheckedChanged;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top