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
如果将它们(例如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)