2014-10-17 143 views
0

如何验证组框中的至少一个单选按钮是否被选中?我正在验证所有的文本控件都是这样正确填充的;验证单选按钮组

 For Each ctrl As Control In Me.Controls 
     If TypeOf ctrl Is TextBox Then 
      If ctrl.Text = "" Then 
       MessageBox.Show("Please enter information in " & ctrl.Name, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) 
       Exit Sub 
      End If 
     End If 

是否有一个类似的单选按钮的方法,因为我似乎无法找到完成此操作的逻辑方法。

+0

当你的布局形式,你可以(应该)设置一个作为默认,用户斜面取消任何和你不会有在执行任何检查。否则复选框将在GroupBox.Controls中找到而不是Me.Controls – Plutonix 2014-10-17 11:56:40

+0

当然可以!我在想。 – 2014-10-17 13:02:54

回答

0

您可以使用LINQ

Dim uncheckedRadios = From radio In Me.groupbox1.Controls.OfType(Of RadioButton)() 
         Where Not radio.Checked 
         Select radio.Name 
Dim anyUnchecked As Boolean = uncheckedRadios.Any() 

If anyUnchecked Then 
    Dim uncheckedNames = String.Join(",", uncheckedRadios) 
    MessageBox.Show("Please check all radio-buttons, these are not checked: " & uncheckedNames, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) 
    Return 
End If