Reputation: 148
Pls I need your help in some cases about button in C#. How can I know when a particular button is clicked. I want to use the if condition statement to write the event. So I want it to do something when particular button is clicked. I want to put all the code inside one function or class then I can call it anytime. For example
private void showPanel()
{
if (dashPanelButton.Clicked == true)
{
dashPanel.Visible = true;
}
else if(studInfoBtn.Clicked == true)
{
studInfoPanel.Visible = true;
}
else
{
homePanel.Visible = true;
}
}
Note the above code is just an assumption not really a working code. Just using it to explain myself
Upvotes: 0
Views: 7483
Reputation: 288
You can do what you want, like this:
private void showPanel(Object sender, EventArgs e)
{
if (sender == dashPanelButton)
{
dashPanel.Visible = true;
}
else if (sender == studInfoBtn)
{
studInfoBtn.Visible = true;
}
else
{
homePanel.Visible = true;
}
}
make sure your button is wired correctly
dashPanelButton.Click += new EventHandler(showPanel);
studInfoBtn.Click += new EventHandler(showPanel);
Upvotes: 0
Reputation: 219057
You don't "check if a button is clicked". The code isn't going to just sit around and wait for that click to happen. Instead, you "respond to a button click" with a click event handler:
void myButton_Click(Object sender, EventArgs e)
{
// do something when the button is clicked
}
You can attach the handler to the button in the designer, or in code:
myButton.Click += new EventHandler(myButton_Click);
Now, if you want the same handler to be used for multiple buttons, that's where that Object sender
becomes useful. That's a reference to the object which raised the event. So in your case, it would be the button which was clicked:
void myButton_Click(Object sender, EventArgs e)
{
var theButton = (Button)sender;
// now "theButton" is the button which was clicked
}
Upvotes: 2
Reputation: 77926
Register the button Click
event and do whatever you want in the event handler like
dashPanelButton.Click += new EventHandler(myhandler);
protected void myhandler(object sender, EventArgs e)
{
//do whatever you want
}
Upvotes: 0