vb.net 获取在 Groupbox 中选中哪个单选按钮

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

Getting Which Radio Button is Checked in a Groupbox

.netvb.netradio-buttongroupbox

提问by hajime_saitou

Found this in here. Could someone explain how this works? especially starting from the Function line.

在这里找到了这个。有人可以解释这是如何工作的吗?特别是从功能线开始。

 Dim rButton As RadioButton = 
    GroupBox1.Controls
   .OfType(Of RadioButton)
   .Where(Function(r) r.Checked = True)
   .FirstOrDefault()

REFERENCE: How to get a checked radio button in a groupbox?

参考:如何在 groupbox 中获得选中的单选按钮?

回答by Jet

So what the above line of code is doing is slowly narrowing down to the selected checkbox. It starts with the group, and then grabs all the controls inside of that groupbox , it then selects only the controls that are radio buttons, then selects only radio buttons that have the checked field set to true, and then selects the first radio button that fits all of this criteria, of which there should only be one.

所以上面这行代码正在做的是慢慢缩小到选中的复选框。它从组开始,然后抓取该 groupbox 内的所有控件,然后仅选择作为单选按钮的控件,然后仅选择已选中字段设置为 true 的单选按钮,然后选择第一个单选按钮符合所有这些标准,其中应该只有一个。

回答by Agustin Meriles

That's called LINQ.

这就是所谓的 LINQ。

Givin a collection of objects (so is GroupBox1.Controls, a collection of RadioButtonobjects), you can query the collection. So, you have a query that retrieves the First RadioButton (or null if there aren't any by using FirstOrDefault) from the RadioButton collection that satisfy the condition of being checked (Function(r) r.Checked = Trueit's a lambda expression). Because Controlsis a collection of objects, you need to cast the to RadioButtonso, you can access the IsCheckedproperty. Hope the explanation helps; anyway you must check the LINQ reference for VB

得到安宁对象的集合(所以是GroupBox1.Controls,一个集合RadioButton对象),您可以查询集合。因此,您有一个查询,可以FirstOrDefault从 RadioButton 集合中检索满足被检查条件(Function(r) r.Checked = True它是一个 lambda 表达式)的第一个 RadioButton(如果没有,则为 null,如果没有,则使用 using )。因为Controls是对象的集合,RadioButton所以需要强制转换,才能访问IsChecked属性。希望解释有帮助;无论如何,您必须检查VBLINQ 参考

回答by tinstaafl

It's probably more efficient to handle all the Checkedchanged events with one handler, instead of iterating through all your radiobuttons:

使用一个处理程序处理所有 Checkedchanged 事件可能更有效,而不是遍历所有单选按钮:

    private void radioButton_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton rb = (RadioButton)sender;
        if (rb.Checked)
            MessageBox.Show(rb.Name);
    }