As many reported on the newsgroups (including me!), the
CheckedListBox control forgets which item is checked when the items have been filled using the
DataSource property and when its
Visible property is set to false, then back to true. The problem also occurs when it is hosted on a
TabControl and tabs are flipped.
I first ran into this issue in my first week of .NET development. Very frustrating start! Since then, I tried many workarounds but all were just an extreme pain in the neck, especially when I was trying to use them on more complex forms.
Those workarounds included never setting the Visible property of the
False. Rather, I moved the control outside the form (ex: -5000, -5000). It worked (most of the time), but some clients reported the problem even with this.
I also tried saving all the checks in an array before setting
alse, then putting them back in the
Visible=true but once again, I felt it was a quite ineffective way.
Back then, I did not know that this bug was related to the
Datasource property. I recently figured this out after pulling my hair for a couple hours. I finally came up with a great and easy workaround...
As I mentioned earlier, the problem only occurs when
DataSource is used to add the items to the
CheckedListBox. So the idea is, you guessed it, to NOT use
DataSource! Here's the code I came up with:
Private Sub SetClBoxDataSource(ByVal clb As CheckedListBox,
ByVal dt As DataTable)
Dim x As Integer
For x = 0 To dt.DefaultView.Count - 1
Basically, what this code does is adding the items one by one using a simple loop. Now, instead of using this code to fill up the
CheckedListBox.DataSource = DataTable
You should do:
It couldn't be easier! Only one line of code to change!