10

我正在尝试创建一个 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

但我得到了错误:

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

4

3 回答 3

18

假设没有嵌套控件:

For Each c As TextBox In Panel1.Controls.OfType(Of TextBox)()
  If c.Text = String.Empty Then c.BackColor = Color.LightYellow
Next
于 2012-11-22T00:45:21.417 回答
16

您可以尝试这样的事情:

  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
于 2012-11-22T00:41:24.143 回答
3

尝试这个。当您输入数据时,它也会恢复颜色

    For Each c As Control In Panel1.Controls
        If TypeOf c Is TextBox Then
            If c.Text = "" Then
                c.BackColor = Color.LightYellow
            Else
                c.BackColor = System.Drawing.SystemColors.Window
            End If
        End If
    Next

还有一种不同的方法可以做到这一点,包括创建一个继承的 TextBox 控件并在您的表单上使用它:

Public Class TextBoxCompulsory
    Inherits TextBox
    Overrides Property BackColor() As Color
        Get
            If MyBase.Text = "" Then
                Return Color.LightYellow
            Else
                Return DirectCast(System.Drawing.SystemColors.Window, Color)
            End If
        End Get
        Set(ByVal value As Color)

        End Set
    End Property
End Class
于 2012-11-22T00:41:04.350 回答