CJ7
CJ7

Reputation: 23285

How to sync up to different events in Winforms

If I have a button which does something and also a double-click event on a data grid which I want to do the same thing, what is the best way to ensure that only one function has to be maintained?

Apart from doing the following, is there any fancy C# way to indicate that two events are to do the same thing?

void button1_Click(...) { MyFunction(); }
void dataGrid1_DoubleClick(...) { MyFunction(); }
void MyFunction() {  // do stuff  }

Upvotes: 0

Views: 226

Answers (3)

Steve
Steve

Reputation: 216313

I suppose that you are talking about a DataGridView (WinForms) so the signature of the event DoubleClick in the DataGridView and the signature of Click event on a button control is the same. (An EventHadler). In this case you can simply set the same method using the form designer or manually bind the event

dataGridView1.DoubleClick += new EventHandler(MyFunction);
button1.Click += new EventHandler(MyFunction);

Of course the MyFunction method should match the expected signature of an EventHandler

private void MyFunction(object sender, EventArgs e)
{
   // do your work
}

Reviewing my answer after a few minutes I wish to add:

If you find yourself in a situation in which you need to differentiate between the controls using the sender object (like Control c = sender as Control; if (c.Name == "someName") ) I really suggest you to return to the first idea. Call a common method but keep the EventHandler separated for each control involved.

Upvotes: 1

JMK
JMK

Reputation: 28069

Just to add to what Steve said, you will want to bind these events to your function manually in the Load event of your form, instead of using the events under the lightning bolt in the properties window in the designer, like so:

private void Form1_Load(object sender, EventArgs e)
{
    button1.Click += MyMethod;
    dataGridView1.DoubleClick += MyMethod;
}

void MyMethod(object sender, EventArgs e)
{
    //Do Stuff
}

Also, declaring a new instance of the EventHandler class has been redundant since Anonymous methods were introduced to C#, you can just point the event directly at the method as shown above.

Upvotes: 0

user1300630
user1300630

Reputation:

Using VS, in the form's designer view You can set the procedure You want to call to each control's each event in the control's properties window.

image

Upvotes: 0

Related Questions