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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With