Anders
Anders

Reputation: 101569

Programmatically triggering System.Windows.Forms.Control event

Let's say I have a Checkbox control:

CheckBox cb = new CheckBox();
cb.CheckedChanged += delegate(object sender, EventArgs e)
{
    MessageBox.Show("hello");
};

How can I programmatically trigger this event?

I can do

cb.Checked = !cb.Checked;
cb.Checked = !cb.Checked;

but that is ugly and will trigger it twice...

Upvotes: 0

Views: 1263

Answers (1)

Fredrik Mörk
Fredrik Mörk

Reputation: 158289

I would refactor your code:

CheckBox cb = new CheckBox();
cb.CheckedChanged += delegate(object sender, EventArgs e)
{
    ShowMessageBox();
};

private void ShowMessageBox()
{
    MessageBox.Show("hello");
}

Now, call ShowMessageBox instead of trying to simulate events. Pass along whatever information you need from the event to the method, in case it needs more to carry out its task:

cb.CheckedChanged += delegate(object sender, EventArgs e)
{
    ShowMessageBox(cb.Checked);
};

private void ShowMessageBox(bool checkedValue)
{
    MessageBox.Show(string.Format("The box was {0}checked", 
        checkedValue ? "" : "un"));
}

Upvotes: 4

Related Questions