VB.NET:代码不检查面板中是否存在控件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14476974/
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
VB.NET: Code does not check if control exists in panel
提问by Ekrem O?UL
My code :
我的代码:
Rs.Open("Select * From Notifications",Con)
If Not Rs.EOF Then
For i=0 to Rs.RecordCount -1
Dim Label As New Label
With Label
.Name = String.Format("Label_{0}",Rs("Id").Value.ToString)
.Text = Rs("Notification").Value.ToString
End With
If Not Panel.Controls.Contains(Label) Then
Panel.Control.Add(Label)
End If
Rs.MoveNext()
Next
End If
But this always adds control to panel, the following code line is not executed correctly:
(If Not Panel.Controls.Contains(Label) Then)
但这总是向面板添加控制,以下代码行未正确执行:
(If Not Panel.Controls.Contains(Label) Then)
This code works in timer.
此代码适用于计时器。
回答by SysDragon
Function CntrlExistsIn(ctrlName as String, parent as Control) as Boolean
Dim bResult as Boolean = False
For Each elem as Control In parent.Controls
If elem.Name = ctrlName Then
bResult = True
Exit For
End If
Next
Return bResult
End Function
The above function is to check whether control(label) exists in Panel or not.
上面的功能是检查面板中是否存在控件(标签)。
回答by andy
There is another way to reduce your code like below
还有另一种减少代码的方法,如下所示
If panel1.Controls.Find(Label.Name, True).Length = 0 Then
panel1.Control.Add(Label)
End If
Controls.Find(controlName,True/False)------True/Falseis for to check in child controls of specified control
Controls.Find(controlName,True/False)------ True/False用于检入指定控件的子控件

