[英]How to trigger radio button's event handler programmatically?
please have a look at the following code 请看下面的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace calc
{
public partial class Form1 : Form
{
//code removed
public Form1()
{
InitializeComponent();
calculator = new Calculator();
maleRadio.PerformClick();
englishRadio.PerformClick();
}
/*code removed*/
//Action Listener for Female Radio button
private void femaleRadio_CheckedChanged(object sender, EventArgs e)
{
//code removed
}
//Action Listener for English Radio button
private void englishRadio_CheckedChanged(object sender, EventArgs e)
{
//code removed
}
}
}
I am somewhat new to c#. 我对c#有些新意。 what I want to do here is to trigger the event handlers
of radio buttons inside the constructor programatically. 我想在这里做的是以编程方式触发构造函数中的单选按钮的event handlers
程序。 The way I followed maleRadio.PerformClick();
我跟着maleRadio.PerformClick();
do nothing. 没做什么。 how can I call the event handlers inside the constructor programmertically ? 如何在构造函数程序中调用事件处理程序?
You can call the event handlers like any other method: 您可以像任何其他方法一样调用事件处理程序:
public Form1()
{
InitializeComponent();
calculator = new Calculator();
maleRadio_CheckedChanged(maleRadio, null);
englishRadio_CheckedChanged(englishRadio, null);
}
You can just call the function femaleRadio_CheckedChanged
on your constructor. 你可以在你的构造函数上调用函数femaleRadio_CheckedChanged
。 Or you can set the value of the selected index of the radiobutton to trigger the event: 或者,您可以设置radiobutton的所选索引的值以触发事件:
femaleRadio_CheckedChanged(null, null);
or
femaleRadio.SelectedIndex = 0;
Just call the method: 只需调用方法:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
radioButton1.CheckedChanged += radioButton1_CheckedChanged;
//Triggering the handlers programmatically
radioButton1_CheckedChanged(null, null);
radioButton2_CheckedChanged(null, null);
}
//this handler is manually added in the constructor
void radioButton1_CheckedChanged(object sender, EventArgs e)
{
Console.WriteLine("Test event 1");
}
//This handler is auto-generated by designer, after adding the event in the designer
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
Console.WriteLine("Test event 2");
}
}
Output is going to be: 输出将是:
Test event 1 Test event 2 Test event 1 测试事件1测试事件2测试事件1
because after the constructor has finished, radiobutton1 will be selected as default. 因为构造函数完成后,将选择radiobutton1作为默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.