Hiding/showing a label when a listbox is hidden/shown
I've got some listboxes with labels on them and I want the label above each listbox to be hidden when the listbox is hidden. Right now I'm giving them matching tags and then just looping to search for the correct one:
Code:
'this subroutine covers concealing all listboxes
Private Sub DisableListboxes(sender As Object, e As EventArgs) Handles Listbox1.EnabledChanged, _
Listbox2.EnabledChanged, Listbox3.EnabledChanged
'the name of the listbox that raised the sub
Dim CurrentList As ListBox = DirectCast(sender, ListBox)
'finds the label associated with that listbox
Dim CurrentLabel As Label = Nothing
For Each lb As Control In CurrentList.Parent.Controls
If TypeOf lb Is Label Then
If CStr(lb.Tag) = CStr(CurrentList.Tag) Then
'it's the correct one
CurrentLabel = DirectCast(lb, Label)
End If
End If
Next lb
If CurrentList.Enabled = False Then
'conceals the label
CurrentLabel.Enabled = False
Else
'reveals the label
CurrentLabel.Enabled = True
End If
End Sub
There has to be a better way.
Re: Hiding/showing a label when a listbox is hidden/shown
Just set the visibility based on the listbox's visibility:
Code:
<label>.Visibility = <listbox>.Visibility
no need for loops.
Edit - I just realized you're using the .Enabled property:
Code:
<label>.Enabled = <listbox>.Enabled
Re: Hiding/showing a label when a listbox is hidden/shown
Several but the easiest is to put each listbox with its label on a separate panel and change the visibility of the panel thusly,
vb.net Code:
Private Sub DisableListboxes(sender As Object, e As EventArgs) Handles ListBox1.EnabledChanged, ListBox2.EnabledChanged 'etc.
If CType(sender, ListBox).Enabled = False Then
CType(sender, ListBox).Parent.Visible = False
Else
CType(sender, ListBox).Parent.Visible = True
End If
End Sub
Re: Hiding/showing a label when a listbox is hidden/shown
dday: The problem is that the subroutine is handling multiple listboxes and I need to find the label that goes with that particular listbox.
dunfiddlin: That'll work. I thought about putting them in a groupbox but it would have been to cluttered; a panel will work well though.
Re: Hiding/showing a label when a listbox is hidden/shown
Another way could be to use a dictionary.
Some thing like
vb Code:
Public Class Form1
Private m_dictionary As New Dictionary(Of ListBox, Label) From
{{Me.ListBox1, Me.Label1},
{Me.ListBox2, Me.Label2},
{Me.ListBox3, Me.Label3}}
Private Sub ListBox1_EnabledChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles _
ListBox1.EnabledChanged,
ListBox2.EnabledChanged,
ListBox3.EnabledChanged
Dim lb As ListBox = DirectCast(sender, ListBox)
Dim l As Label = Me.m_dictionary(lb)
l.Enabled = lb.Enabled
End Sub
End Class
Re: Hiding/showing a label when a listbox is hidden/shown
Say Label1 is paired with ListBox1
In form load
Code:
Label1.DataBindings.Add("Visible", ListBox1, "Visible")
Test it say in a button click event
Code:
ListBox1.Visible = Not ListBox1.Visible