0

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?

Community
  • 1
  • 1
alois
  • 159
  • 5
  • 16

3 Answers3

1

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.

Jet
  • 43
  • 5
1

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

Agustin Meriles
  • 4,866
  • 3
  • 29
  • 44
  • What's FirstOrDefault for? – alois Oct 11 '13 at 17:36
  • 1
    `FirstOrDefault`, (as `First`) retieves the First item of the collection, with the only difference that `FirstOrDefault` retrieves a default value (generally null) if there are no 'first' item. `First` will throw an exception in that case. – Agustin Meriles Oct 11 '13 at 17:38
0

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);
    }
tinstaafl
  • 6,908
  • 2
  • 15
  • 22