3

In my winform, in the designer.cs section of the form i have

this.Button1.Text = "&Click";
this.Button1.Click += new System.EventHandler(this.Button1_Click);

in form.cs

 private void Button1_Click(object sender, System.EventArgs e)
 {
     //Code goes here.
 }

In one part of the form i have a treeview and when that treeview contents are expanded, i need to rename the above button and wire up a different event

  Button1.Name = "ButtonTest";
  ButtonTest.Click += new System.EventHandler(this.ButtonTest_Click);

However this fails saying ButtonTest is not found, how do i dynamicall change the name of the button and call a different click event method?

 private void ButtonTest_Click(object sender, System.EventArgs e)
 {
     //Code goes here.
 }

Once this is called ButtonTest_Click, I need to rename it back to Button1, any thoughts?

Sharpeye500
  • 8,775
  • 25
  • 95
  • 143

2 Answers2

6

Button1 refers to a variable name. The variable points to an instance of the Button type which has a Name property. If you change the value of the Name property, it doesn't change the name of the variable. You'll still need to refer to the button as button1. In fact, it does nothing really to change the value of the button's Name property. The Name property only really only exists to aide the Windows Forms designer.

If you want to change an event handler from one method to another, you must first unsubscribe the original handler and then subscribe the new handler. Just change your code to this:

Button1.Name = "ButtonTest";
Button1.Click -= this.Button1_Click;
Button1.Click += this.ButtonTest_Click;
Dan
  • 9,717
  • 4
  • 47
  • 65
  • I too had this in my code, but the code of Button1_click gets called instead of ButtonTest_Click. In other words, code in Button1_click gets called first then code in ButtonTest_Click gets called next. – Sharpeye500 Aug 08 '12 at 00:02
  • 1
    You need to remove the old EventHandler first using -= directive http://stackoverflow.com/questions/1307607/removing-event-handlers – Moop Aug 08 '12 at 00:07
  • I originally failed to mention that you must first unsubcribe the original handler. I've edited the answer to reflect this. – Dan Aug 08 '12 at 00:07
0

This can be done by several ways:

  1. From the Menus: Edit -> Refactor -> Rename

  2. By contextual Menu on the name of the Method: Refactor -> Rename

  3. Put the cursor on the Method name and type Alt + Shift + F10 and then select Rename

  4. Put the cursor on the Method name and press F2

legoscia
  • 39,593
  • 22
  • 116
  • 167