VB.NET: Code does not check if control exists in panel
11,858
Solution 1
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.
Solution 2
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/False is for to check in child controls of specified control
Author by
Ekrem OĞUL
Updated on June 13, 2022Comments
-
Ekrem OĞUL almost 2 years
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)
This code works in timer.
-
SysDragon over 11 yearsI dont understand what do you want
-
andy over 11 yearsCheck "Id" and "Notification"........... Its coming different for each loop
-
Ekrem OĞUL over 11 yearsthis code work in timer and check a minute. if notification is show in panel then i dont want to add new. if not show notification(is new) then i want to add to panel with new control label.
-
-
Ekrem OĞUL over 11 yearsThanks SysDragon. I Tray If Not Panel.Controls.Contains(Label) Then but search in controls with control name is working. thank you so much.
-
Konrad Rudolph over 11 yearsThis code can be shortened by almost half by removing the useless variable and returning immediately.
-
SysDragon over 11 years@KonradRudolph I know, but Im used to do bigger functions and I prefer to follow best programming practices. Only one
return
is clearer. -
Konrad Rudolph over 11 years@SysDragon No no, it’s the other way round. If you want to follow best practices, make your functions smaller. Also, “single return” has never been a best practice, it’s a completely misunderstood concept.
-
SysDragon over 11 years@KonradRudolph Well, looks like it's a very controversial topic. Theres people and experts saying both things. =/
-
Konrad Rudolph over 11 years@SysDragon No, it’s not at all controversial, simply a misunderstanding. There’s an explanation here: programmers.stackexchange.com/a/118793/2366, and here are some reasons to explain why, even though it might make sense in C, it never makes sense in languages such as VB: programmers.stackexchange.com/a/118717/2366
-
SysDragon over 11 years@KonradRudolph Thanks for the information. Very interesting. Ill consider changing my practice for small or even medium functions.