When data is retrieved from my database and placed in a listbox, the first item is always selected. However, I do not want that behavior. How do you programatically unselect items in a listbox?
I know how to do it using a webform listbox, but the windowsform listbox does not work the same way.
I even tried the ClearSelected() method and still did not work........
I don't know why it's so hard to programaticlly unselect items from a listbox. Clearly, all the methods I've tried do not clear the selected items. I'm wondering if there is a bug with this functionality in .Net...............
fyi, I have a dataset bound to the listbox with a valuemember & display member column.
Well, yes, interesting hacks. Should it be this difficult?
BTW, your solution (and my original one, along with the ClearSelection method--that is, all the techniques) work if you're just filling in the list manually. It's when you bind to a data source that nothing works.
Well, if you're interested in a slimy hack, I have one that appears to work. It involves subclassing the listbox:
Public Class MyListBoxSubClasser
Private Const LB_SETCURSEL As Integer = &H186
Public Sub New(ByVal hWnd As IntPtr)
Public Sub Dispose()
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = LB_SETCURSEL Then
m.WParam = IntPtr.op_Explicit(-1)
Then, when you are assigning your datasource to the listbox:
Dim ml As New MyListBoxSubClasser(ListBox1.Handle)
Ensure, though, that you call dispose on the object above when you are done with it. I played around with this for about 20 minutes and the only instance that the LB_SETCURSEL message seemed to be coming through was when the datasource was being set... Programmatic or User initiated selection did not result in this message.
Hope this helps, let me know if you have questions.