我这里有代码可以更改列表框突出显示的颜色。但是,当列表框为空时,会给出错误 InvalidArgument =值-1,对于'index'无效。 参数名称:索引 表格将进入无响应状态。
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
有人可以帮助我吗?
答案 0 :(得分:1)
如果没有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