如何检测哪个按钮被点击在code后面? [英] How to detect which button was clicked in code behind?
问题描述
我对他们的的onClick
事件三个按钮调用每个 btn_Clicked
。在code后面,我想导致回发按钮的ID。我知道我可以分配每个按钮调用不同的方法,但我想了解一些ASP.Net的。还告诉我,哪种方法更有效?调用不同的按钮点击不同的方法或调用相同的方法(如果每个按钮的功能是一样的)。
铸造发送对象按钮,然后你可以得到所有的属性。
按钮clickedButton =(按钮)发送;
还告诉我哪种方法更有效?调用不同的方法
在不同的按钮点击或调用同样的方法(如果
每个按钮的功能是一样的)。
块引用>如果功能相同则最好有一个单一的事件,因为你没有复制code。记住 DRY原则。
请看下面的例子:
保护无效的button1_Click(对象发件人,EventArgs的发送)
{
按钮clickedButton =发件人的按钮; 如果(clickedButton == NULL)//只是为了安全起见
返回; 如果(clickedButton.ID ==Button1的)
{
}
否则,如果(clickedButton.ID ==将Button2)
{
}
}I have three buttons each calling
btn_Clicked
on theironClick
event. In code behind I want to get the ID of the button that caused postback. I know I can assign each button to call a different method but I would like to learn a bit of ASP.Net. Also tell me which method is more efficient? Calling different methods on different button clicks or calling the same method (if the functionality of each button is same).解决方案Cast the sender object to the button and then you can get all the properties.
Button clickedButton = (Button)sender;
Also tell me which method is more efficient? Calling different methods on different button clicks or calling the same method (if the functionality of each button is same).
If the functionality is same then it's better to have a single event, since you don't have to replicate code. Remember the DRY principle.
Consider the following example:
protected void Button1_Click(object sender, EventArgs e) { Button clickedButton = sender as Button; if (clickedButton == null) // just to be on the safe side return; if (clickedButton.ID == "Button1") { } else if(clickedButton.ID == "Button2") { } }
这篇关于如何检测哪个按钮被点击在code后面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!