if the user clicks on an invalid selection i want to set the selectionindex
to -1 so there is nothing selected, unfortunately it doesn't work
i followed the code through with the debugger and everything works fine
right up till the very end when an extra selectedindexchanged event is fired
and the index is set to ZERO for absolutely no reason whatsoever
however this is ONLY a problem if the list is bound to a dataview, not if it
is populated manually
to reproduce create a form with two listboxes, lst1 and lst2, and paste in
the code below
when it runs click on the '30' in lst1 and then click on the 'x'. The
selectedindex goes to -1 which is the correct behavior
do the same thing with lst2 and the selection will jump to index zero!
the code handling the two listboxes is identical and yet produces very
different results
for lst2 you have to click the 'x' twice in order for the selection to
disappear
Private Sub Form1_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles MyBase.Load
lst1.Items.Add("20")
lst1.Items.Add("x")
lst1.Items.Add("30")
Dim dt As New DataTable
dt.Columns.Add("ListName", GetType(String))
Dim dr As DataRow
dr = dt.NewRow
dr("ListName") = 20
dt.Rows.Add(dr)
dr = dt.NewRow
dr("ListName") = "x"
dt.Rows.Add(dr)
dr = dt.NewRow
dr("ListName") = 30
dt.Rows.Add(dr)
Dim dv As New DataView(dt)
lst2.DataSource = dv
lst2.DisplayMember = "ListName"
End Sub
Private Sub lst1_SelectedIndexChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles lst1.SelectedIndexChanged
lstclick(lst1)
End Sub
Private Sub lst2_SelectedIndexChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles lst2.SelectedIndexChanged
lstclick(lst2)
End Sub
Private Sub lstclick(ByVal lst As ListBox)
If lst.SelectedIndex = -1 Then Exit Sub
If Not ValCheck(lst.Text) Then
lst.SelectedIndex = -1
Exit Sub
End If
End Sub
Private Function ValCheck(ByVal val As String) As Boolean
Return IsNumeric(val)
End Function
End Class
|