如何在组合框中获取已选中的单选按钮?

Pre*_*tor 17 .net vb.net visual-studio-2010 radio-button winforms

我在组合框中有很多单选按钮.通常我会单独检查每个单选按钮If radiobutton1.Checked = True Then.

但我想也许有一种聪明的方法来检查在一个组框中检查哪个单选按钮.任何的想法?

Bin*_*nil 45

试试这个

Dim rButton As RadioButton = 
        GroupBox1.Controls
       .OfType(Of RadioButton)
       .FirstOrDefault(Function(r) r.Checked = True)
Run Code Online (Sandbox Code Playgroud)

这将返回Checked RadioButtonin aGroupBox

请注意,这是一个LINQ查询,您必须拥有

Imports System.Linq
Run Code Online (Sandbox Code Playgroud)

如果不这样做,您的IDE /编译器可能会指出OfType不是其成员System.Windows.Forms.Control.ControlCollection

  • 这是一个很好的解决方案.您可以通过将.Shere替换为.SingleOrDefault并删除.FirstOrDefault来使其更简单. (4认同)
  • 您不需要`Where`,因为您也可以将Lambda表达式传递给`FirstOrDefault()`方法. (3认同)

Ern*_*rno 8

如果将它们(例如Load事件)添加到List,则可以使用LINQ:

Dim checkedRadioButton as RadioButton
checkedRadioButton = 
    radioButtonList.FirstOrDefault(Function(radioButton) radioButton.Checked))
Run Code Online (Sandbox Code Playgroud)

这应该没问题,因为最多只检查一个.

编辑 更好:只查询GroupBox的Controls集合:

Dim checkedRadioButton as RadioButton
checkedRadioButton = 
    groupBox.Controls.OfType(Of RadioButton)().FirstOrDefault(Function(radioButton) radioButton.Checked))
Run Code Online (Sandbox Code Playgroud)

请注意,如果Groupbox中没有RadioButtons,这将导致问题!


小智 6

'returns which radio button is selected within GroupBox passed
Private Function WhatRadioIsSelected(ByVal grp As GroupBox) As String
    Dim rbtn As RadioButton
    Dim rbtnName As String = String.Empty
    Try
        Dim ctl As Control
        For Each ctl In grp.Controls
            If TypeOf ctl Is RadioButton Then
                rbtn = DirectCast(ctl, RadioButton)
                If rbtn.Checked Then
                    rbtnName = rbtn.Name
                    Exit For
                End If
            End If
        Next
    Catch ex As Exception
        Dim stackframe As New Diagnostics.StackFrame(1)
        Throw New Exception("An error occurred in routine, '" & stackframe.GetMethod.ReflectedType.Name & "." & System.Reflection.MethodInfo.GetCurrentMethod.Name & "'." & Environment.NewLine & "  Message was: '" & ex.Message & "'")
    End Try
    Return rbtnName
End Function
Run Code Online (Sandbox Code Playgroud)

  • 其他答案更简洁一些,但这作为一种不需要控件名称的蛮力方法很有趣。 (2认同)