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?

有帮助吗?

解决方案

That's called LINQ.

Givin a collection of objects (so is GroupBox1.Controls, a collection of RadioButton objects), 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 = True it's a lambda expression). Because Controls is a collection of objects, you need to cast the to RadioButton so, you can access the IsChecked property. Hope the explanation helps; anyway you must check the LINQ reference for VB

其他提示

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.

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

    private void radioButton_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton rb = (RadioButton)sender;
        if (rb.Checked)
            MessageBox.Show(rb.Name);
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top