简体   繁体   English

以编程方式触发事件C#

[英]Fire event programmatically C#

I have several radio buttons inside a container. 我在一个容器中有几个单选按钮。 For each one I have the CheckedChanged event so I have a code like this 对于每一个我都有CheckedChanged事件,所以我有这样的代码

private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
    if ((sender as RadioButton).Checked)
    // do stuff...
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
    if ((sender as RadioButton).Checked)
    // do stuff...
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
    if ((sender as RadioButton).Checked)
    // do stuff...
}
// ... and so on...

Then I must fire the CheckedChanged event for the currently checked radioButton . 然后,我必须为当前选中的radioButton触发CheckedChanged事件。 To get the radioButton I used this code: 为了获得radioButton我使用了以下代码:

RadioButton checkedButton = container.Controls.OfType<RadioButton>()
                            .FirstOrDefault(r => r.Checked);

Now how can I fire the CheckedChanged event for checkedButton ? 现在,如何为checkedButton触发CheckedChanged事件?

EDIT: I'm using WinForms. 编辑:我正在使用WinForms。 My radio buttons are in a tabPage . 我的单选按钮位于tabPage When I open the tabPage I need to know what is the currently checked radioButton and fire the corresponding checkedChanged event. 当我打开tabPage我需要知道什么是当前选中的radioButton并触发相应的checkedChanged事件。 This is because when I select another tabPage I perform other actions and, going back to the tabPage containing the radio buttons, I need to restore the previous state. 这是因为当我选择另一个tabPage我会执行其他操作,然后返回到包含单选按钮的tabPage ,我需要恢复以前的状态。

Changing the value of the Checked property should fire the event: 更改Checked属性的值将触发事件:

checkedButton .Checked = !checkedButton .Checked;

You may also call the event handler explicitly, eg: 您也可以显式调用事件处理程序,例如:

RadioButton checkedButton = container.Controls.OfType<RadioButton>().FirstOrDefault(r => r.Checked);
switch (checkedButton.Name)
{
    case "radioButton1":
        radioButton1_CheckedChanged(this, EventArgs.Empty);
        break;
    case "radioButton2":
        radioButton2_CheckedChanged(this, EventArgs.Empty);
        break;
    case "radioButton3":
        radioButton3_CheckedChanged(this, EventArgs.Empty);
        break;
}

Depending on your requirements, you may of course want to consider using the same event handler for all RadioButtons . 根据您的要求,您当然可以考虑为所有RadioButtons使用相同的事件处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM