Reputation: 323
I have code here that changes the color of the highlight of a listbox. But when the listbox is empty it gives an error InvalidArgument=Value of '-1' is not valid for 'index'. Parameter name: index and the form will go into a not responding state.
Private Sub BranchListBox_DrawItem(sender As Object, e As DrawItemEventArgs) Handles BranchListBox.DrawItem
Dim mybrush As New System.Drawing.SolidBrush(Color.FromArgb(0, 177, 89))
mybrush.Color = Color.FromArgb(0, 177, 89)
Try
e.DrawBackground()
If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
e.Graphics.FillRectangle(mybrush, e.Bounds)
End If
Using b As New SolidBrush(e.ForeColor)
e.Graphics.DrawString(BranchListBox.GetItemText(BranchListBox.Items(e.Index)), e.Font, b, e.Bounds)
End Using
e.DrawFocusRectangle()
Catch ex As Exception
ColorAppend(LogsBox, Color.Red, TimeOfDay.ToString("h:mm:ss") & SystemLog & ex.Message & Environment.NewLine)
LogsBox.ScrollToCaret()
End Try
End Sub
Can anyone please help me?
Upvotes: 1
Views: 1425
Reputation: 43564
You can avoid this event in case there is no ListBox.Item
:
Private Sub BranchListBox_DrawItem(sender As Object, e As DrawItemEventArgs) Handles BranchListBox.DrawItem
'exit this event in case there is not valid index.
If e.Index = -1 Then
Exit Sub
End If
Dim mybrush As New System.Drawing.SolidBrush(Color.FromArgb(0, 177, 89))
mybrush.Color = Color.FromArgb(0, 177, 89)
Try
e.DrawBackground()
If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
e.Graphics.FillRectangle(mybrush, e.Bounds)
End If
Using b As New SolidBrush(e.ForeColor)
e.Graphics.DrawString(BranchListBox.GetItemText(BranchListBox.Items(e.Index)), e.Font, b, e.Bounds)
End Using
e.DrawFocusRectangle()
Catch ex As Exception
ColorAppend(LogsBox, Color.Red, TimeOfDay.ToString("h:mm:ss") & SystemLog & ex.Message & Environment.NewLine)
LogsBox.ScrollToCaret()
End Try
End Sub
Upvotes: 1