vb.net 对于每个文本框循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13504280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
For each textbox loop
提问by Lift
I'm trying to make a foreach loop that checks every TextBox in a panel and changes BackColor if its Text is nothing. I've tried the following:
我正在尝试创建一个 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
but I'm getting the error:
但我收到错误:
Unable to cast object of type System.Windows.Forms.Label to type System.windows.forms.textbox
无法将 System.Windows.Forms.Label 类型的对象转换为 System.windows.forms.textbox
回答by Neolisk
Assuming there are no nested controls:
假设没有嵌套控件:
For Each c As TextBox In Panel1.Controls.OfType(Of TextBox)()
If c.Text = String.Empty Then c.BackColor = Color.LightYellow
Next
回答by Colin Pear
You might try something like this instead:
你可以试试这样的:
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
回答by Derek Tomes
Try this. It'll put the color back when you enter data as well
尝试这个。当您输入数据时,它也会恢复颜色
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
There is also a different way to do this which involves creating an inherited TextBox control and using that on your form:
还有一种不同的方法可以做到这一点,包括创建一个继承的 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