Reputation: 22995
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#. what I want to do here is to trigger the event handlers
of radio buttons inside the constructor programatically. The way I followed maleRadio.PerformClick();
do nothing. how can I call the event handlers inside the constructor programmertically ?
Upvotes: 5
Views: 13081
Reputation: 371
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
because after the constructor has finished, radiobutton1 will be selected as default.
Upvotes: 1
Reputation: 1166
You can just call the function femaleRadio_CheckedChanged
on your constructor. Or you can set the value of the selected index of the radiobutton to trigger the event:
femaleRadio_CheckedChanged(null, null);
or
femaleRadio.SelectedIndex = 0;
Upvotes: 1
Reputation: 39085
You can call the event handlers like any other method:
public Form1()
{
InitializeComponent();
calculator = new Calculator();
maleRadio_CheckedChanged(maleRadio, null);
englishRadio_CheckedChanged(englishRadio, null);
}
Upvotes: 10