vb.net 检测单选按钮更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15534138/
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-17 12:53:51  来源:igfitidea点击:

Detecting a radiobutton change

vb.netradio-buttondetect

提问by Henry Penton

I have about 50 radiobuttons on one form and I don't want to create an if statement for each one to detect when one changes, they are not part of a group box. How would I detect if any radiobutton changed and then write the name to another variable?

我在一个表单上有大约 50 个单选按钮,我不想为每个单选按钮创建一个 if 语句来检测一个更改的时间,它们不是组合框的一部分。我将如何检测是否有任何单选按钮更改,然后将名称写入另一个变量?

回答by Davido

Put all the radio buttons on a panel and loop through the panels radio button controls, programmatically adding the same event handler for each as described by @Steve. One way I like to handle the event is to assign each radio button an index into its tag property. Then just store any relevant data in a list of objects and access the data for that radio button by pulling out it's corresponding object from the list using its tag. Much easier than doing it by hand.

将所有单选按钮放在面板上并循环浏览面板单选按钮控件,以编程方式为每个按钮添加相同的事件处理程序,如@Steve 所述。我喜欢处理事件的一种方法是为每个单选按钮分配一个索引到其标签属性中。然后只需将任何相关数据存储在对象列表中,并通过使用其标签从列表中拉出对应的对象来访问该单选按钮的数据。比手工做要容易得多。

Edit: Good catch @Neolisk. Updated answer.

编辑:很好的捕获@Neolisk。更新了答案。

回答by Steve

You could Always set the CheckedChanged event for all 50 radiobuttons to the same event handler. This is an example done via code:

您可以始终将所有 50 个单选按钮的 CheckedChanged 事件设置为相同的事件处理程序。这是通过代码完成的示例:

Private Sub OnChange(sender As System.Object, e As System.EventArgs)
    Dim rb = CType(sender, RadioButton)
    Console.WriteLine(rb.Name + " " + rb.Checked.ToString)
End Sub

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    AddHandler Me.RadioButton1.CheckedChanged, AddressOf OnChange
    AddHandler Me.RadioButton2.CheckedChanged, AddressOf OnChange
    ' and so on .....'
End Sub

I have done this via code and not using the designer to avoid the long add of Handles RadioButton1.CheckedChanged, RadioButton2.CheckedChanged .......

我是通过代码完成的,而不是使用设计器来避免长时间添加 Handles RadioButton1.CheckedChanged, RadioButton2.CheckedChanged .......