我正在尝试创建一个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
答案 0 :(得分:15)
假设没有嵌套控件:
For Each c As TextBox In Panel1.Controls.OfType(Of TextBox)()
If c.Text = String.Empty Then c.BackColor = Color.LightYellow
Next
答案 1 :(得分:12)
您可以尝试这样的事情:
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
答案 2 :(得分:2)
试试这个。当您输入数据时它会将颜色恢复原状
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