How can you have a single event handler for Multiple Buttons?
Is there a way to simplify the code?
Like for example if you have button 1 that nagivate to another page. Then you have another Button that fires an event.
How can you create a single Event handler for both or more in C sharp VS 2013?
Thank you!!!!
Loading
VulpesPosted Sep 29, 2014, 5:41 PM
int btnNum = ((Button)sender).Name[6] - 48;
This works by taking the 7th (and last character of the name) which will be '1' to '6'. These characters have an ASCII value of 49 to 54 so if we deduct 48, we will get the actual integer value of the character.
You can then use that integer (minus 1) as an index into your 'urls' array and navigate to it.
VulpesPosted Sep 29, 2014, 5:54 PM
Matt brownPosted Sep 29, 2014, 5:46 PM
Matt brownPosted Sep 29, 2014, 5:27 PM
VulpesPosted Sep 29, 2014, 5:21 PM
If the buttons are numbered consecutively - button1 to button6 - then you could determine which one was pressed with one line of code :
int btnNum = ((Button)sender).Name[6] - 48;
If you then have a string array with 6 urls, you could navigate to the appropriate one which would be urls[btnNum - 1].
Matt brownPosted Sep 29, 2014, 5:06 PM
Like I have 6 buttons. They all navigate to some pages. Is there any way to wrap them in a few line of code? Basically all they are use for is nagivation.
Thank you
VulpesPosted Sep 29, 2014, 4:21 PM
You can also do this dynamically in code like this:
button1.Click += button_Click;
button2.Click += button_Click; // same handler
and ascertain which button was actually pressed using the 'sender' parameter:
private void button_Click(object sender, RoutedEventArgs e)
{
Button b = (Button)sender;
if (b.Name == "button1")
{
// do something
}
else if (b.Name == button2)
{
// do something else
}
}