VB.NET:代码不检查面板中是否存在控件

时间:2013-01-23 10:04:50

标签: vb.net controls

我的代码:

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

但这总是会向面板添加控件,以下代码行未正确执行: (If Not Panel.Controls.Contains(Label) Then)

此代码适用于计时器。

2 个答案:

答案 0 :(得分:3)

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

以上功能是检查Panel中是否存在控件(标签)。

答案 1 :(得分:0)

还有另一种方法可以减少您的代码,如下所示

 If panel1.Controls.Find(Label.Name, True).Length = 0 Then
    panel1.Control.Add(Label)
 End If  

Controls.Find(controlName,True / False)------ True/False 用于签入指定控件的子控件