对于每个文本框循环

Lif*_*ift 8 vb.net

我正在尝试创建一个foreach循环来检查面板中的每个TextBox,如果Text没有,则更改BackColor.我尝试过以下方法:

Dim c As TextBox
For Each c In Panel1.Controls
  if c.Text = "" Then
    c.BackColor = Color.LightYellow
  End If
Next
Run Code Online (Sandbox Code Playgroud)

但是我收到了错误:

无法将System.Windows.Forms.Label类型的对象强制转换为System.windows.forms.textbox类型

Neo*_*isk 15

假设没有嵌套控件:

For Each c As TextBox In Panel1.Controls.OfType(Of TextBox)()
  If c.Text = String.Empty Then c.BackColor = Color.LightYellow
Next
Run Code Online (Sandbox Code Playgroud)


Col*_*ear 13

您可以尝试这样的事情:

  Dim ctrl As Control
  For Each ctrl In Panel1.Controls
  If (ctrl.GetType() Is GetType(TextBox)) Then
      Dim txt As TextBox = CType(ctrl, TextBox)
      txt.BackColor = Color.LightYellow
  End If
Run Code Online (Sandbox Code Playgroud)