问题描述
限时送ChatGPT账号..请我在某些情况下需要你的帮助,关于 C# 中的按钮.我怎么知道什么时候点击了一个特定的按钮.我想使用 if 条件语句来编写事件.所以我希望它在点击特定按钮时做一些事情.我想将所有代码放在一个函数或类中,然后我可以随时调用它.例如
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
推荐答案
您不会检查按钮是否被点击".代码不会只是坐在那里等待点击发生.相反,您使用点击事件处理程序响应按钮点击":
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);
现在,如果您希望将相同的处理程序用于多个按钮,那么 Object sender
就变得有用了.这是对引发事件的对象的引用.所以在你的情况下,这将是被点击的按钮:
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
}
这篇关于在 C# 中如何知道何时单击按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论