请查看以下代码
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
}
}
}
我对c#有些陌生。我想在这里用程序触发构造函数内的单选按钮的event handlers
。我遵循maleRadio.PerformClick();
的方式什么也没做。如何以编程方式调用构造函数内部的事件处理程序?
您可以像调用任何其他方法一样调用事件处理程序:
public Form1()
{
InitializeComponent();
calculator = new Calculator();
maleRadio_CheckedChanged(maleRadio, null);
englishRadio_CheckedChanged(englishRadio, null);
}
您可以在构造函数上调用函数femaleRadio_CheckedChanged
。或者,您可以设置单选按钮所选索引的值以触发事件:
femaleRadio_CheckedChanged(null, null);
or
femaleRadio.SelectedIndex = 0;
只需调用方法:
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");
}
}
输出将是:
测试事件1测试事件2测试事件1
因为在构造函数完成之后,radiobutton1将被选择为默认值。