vb.net 获取单击事件中按钮的 ID/名称。网络

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14566156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:38:02  来源:igfitidea点击:

Get the ID/Name of a button in a click event. VB.NET

vb.net

提问by pluke

I have an event in VB.NET to handle several button clicks at once. I need to know which button from the selection kicked off the event. Any ideas how to do this? My code is below:

我在 VB.NET 中有一个事件可以一次处理多个按钮点击。我需要知道选择中的哪个按钮启动了事件。任何想法如何做到这一点?我的代码如下:

Private Sub Answer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnswer1.Click, btnAnswer2.Click, btnAnswer3.Click, btnAnswer4.Click
    'output button ID that caused event
End Sub

I've tried sender.Id, e.Id, sender.name, e.name. None of them work

我试过 sender.Id、e.Id、sender.name、e.name。他们都没有工作

回答by U1199880

You have to cast the sender to the object type expected.

您必须将发件人强制转换为预期的对象类型。

 Dim btn As Button = CType(sender, Button)

Then you can access what you need.

然后您可以访问您需要的内容。

回答by Mark Hall

Try CType(Sender, Button).Name. Sender is an Object you need to cast to the calling Type in this case Button. If you need more properties from the Sender then use U1199880 's answer. But usually when I am trying to handle multiple clicks I will use the Tag property, assign an index to it. Something like this.

试试CType(Sender, Button).Name。Sender 是一个对象,在这种情况下,您需要将其转换为调用 Type 的 Button。如果您需要来自发件人的更多属性,请使用 U1199880 的答案。但通常当我尝试处理多次点击时,我会使用 Tag 属性,为其分配一个索引。像这样的东西。

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click
    Dim index As Integer
    If Not Integer.TryParse(CType(sender, Button).Tag.ToString, index) Then Exit Sub

    Select Case index
        Case 0

        Case 1

        Case 2
            ....
    End Select

End Sub

回答by user7310638

Even simpler:

更简单:

If sender is btnAnswer1 then ...

如果发件人是 btnAnswer1 那么...