I am coding an c#.net application, where i have multiple events for multiple buttons. Now, I wanted to put all that code in a single event and i have to work as it was working previously. Can i use a switch case inside the Event???
Here is the sample code of multiple events:
if (button.SelectSingleNode("ButtonId").InnerText == "btnRefresh")
rButton.Click += new EventHandler
else if (button.SelectSingleNode("ButtonId").InnerText == "btnSaveToVGF")
rButton.Click += new EventHandler
else if (button.SelectSingleNode("ButtonId").InnerText == "btnSubmit")
rButton.Click += new EventHandler
Now, I want to work on a single event and That event should handle all these events code. I mean all the code in btnRefresh_Click, btnSaveToVGF_Click, btnSubmit_Click into a single event button_click. so when i click this any button, this event should be handled and appropriate action should be taken using switch case.
Any help would be greatly appreciated.
Thanks & Regards,
K.S.Reddi Prasad.
theLizardPosted Apr 2, 2011, 6:46 PM
private void my_button_Click (object sender, EventArgs e)
{
switch(((Button)Sender).InnerText)
{
case "btnRefresh":
//do your stuff
break;
case "btnSaveToVGF":
//do your stuff
break;
case "btnSubmit":
//do your stuff
break;
}
}
Whats the problem!!
Sam HobbsPosted Apr 2, 2011, 11:56 AM
You could use a collection such as a Dictionary to relate a Button object to other relevant data.
You could use the Tag property to reference an object with other relevant data.
Either one of those two could eliminate the need for a switch.
A more object-oriented solution would be to derive a class from Button.
VulpesPosted Apr 1, 2011, 8:16 AM
First of all, in the VS Properties Box you'll need to change the Click handlers of all 3 buttons so that they now point to button_Click or whatever you're going to call it.
The code for that button's Click handler will then be:
private void button_Click (object sender, EventArgs e)
{
Button btn = (Button)sender;
switch(btn.Name)
{
case "btnRefresh":
btnRefresh_Click(btn, e);
break;
case "btnSaveToVGF":
btnSaveToVGF_Click(btn, e);
break;
case "btnSubmit"
btnSubmit_Click(btn, e);
break;
}
// anything else you want to do
}
If you're going to remove the existing handlers completely, then just replace the calls to those methods with their actual code.