【问题标题】:For each textbox loop对于每个文本框循环
【发布时间】:2012-11-22 00:34:39
【问题描述】:

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

【问题讨论】:

标签: vb.net


【解决方案1】:

假设没有嵌套控件:

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

【讨论】:

    【解决方案2】:

    你可以试试这样的方法:

      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
    

    【讨论】:

    • 您需要在他们键入文本后将背景颜色设置回来,但本示例无法做到这一点。
    • 在这个特定的例子中,条件可以简化为If (ctrl.GetType() Is GetType(TextBox)) Then ctrl.BackColor = Color.LightYellow...
    【解决方案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-09-01
    • 1970-01-01
    • 2013-11-22
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 2011-07-15
    相关资源
    最近更新 更多