如何以编程方式触发单选按钮的事件处理程序?

时间:2013-07-26 05:39:46

标签: c# .net visual-studio-2010 event-handling radio-button

请查看以下代码

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();的方式什么都不做。如何在构造函数程序中调用事件处理程序?

3 个答案:

答案 0 :(得分:8)

您可以像任何其他方法一样调用事件处理程序:

public Form1()
{
   InitializeComponent();
   calculator = new Calculator();

   maleRadio_CheckedChanged(maleRadio, null);
   englishRadio_CheckedChanged(englishRadio, null);
}

答案 1 :(得分:1)

您只需在构造函数上调用函数femaleRadio_CheckedChanged即可。或者,您可以设置radiobutton的所选索引的值以触发事件:

femaleRadio_CheckedChanged(null, null);
or
femaleRadio.SelectedIndex = 0;

答案 2 :(得分:1)

只需调用方法:

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为默认值。