2014-10-17 142 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