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

VulpesRank #55 · 29.2K reputationPosted Sep 29, 2014, 1:41 PM EDT
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.
VulpesRank #55 · 29.2K reputationPosted Sep 29, 2014, 12:21 PM EDT
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
}
}
VulpesRank #55 · 29.2K reputationPosted Sep 29, 2014, 1:54 PM EDT
Matt brown8 reputationPosted Sep 29, 2014, 1:06 PM EDT
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
VulpesRank #55 · 29.2K reputationPosted Sep 29, 2014, 1:21 PM EDT
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 brown8 reputationPosted Sep 29, 2014, 1:27 PM EDT
Matt brown8 reputationPosted Sep 29, 2014, 1:46 PM EDT