Sharpeye500
Sharpeye500

Reputation: 9063

Changing button name and event handling at run time

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?

Upvotes: 3

Views: 16605

Answers (2)

user7992841
user7992841

Reputation: 1

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

Upvotes: 0

Dan
Dan

Reputation: 9837

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;

Upvotes: 6

Related Questions