使用VIsual Basic 2015动态更改列表框行 [英] Dynamically changing a listbox line using VIsual Basic 2015
问题描述
我想知道是否可以更改列表框中仅包含特定字符的行.例如,我有一个名称列表.我正在使用Visual Basic 2015
I was wondering if it is possible to change lines in a Listbox that have only a certain character in it. For example I have a list of names. I am using Visual Basic 2015
乔
约翰
迈克
*史蒂夫
* Tim
米歇尔
Joe
John
Mike
*Steve
*Tim
Michelle
我想让带有*(或任何特殊字符)的线变成红色.我可以硬编码完全匹配的代码并使它变成红色,但是我的列表框将包含动态信息,因此它一直在变化.我正在标记信息,我想突出显示带有*的信息.感谢您的时间.这是我尝试使用的通用代码的一个小片段.
I would like to make the ones that have the *(or any special character) turn the line Red. I can hard wire in the code exact matches and make it turn red but my listbox will have dynamic information in it so it will be changing all the time. I am marking the information I would like to highlight the information that has the *. Thank you for your time. Here is a small snipet of the generic code I was trying to use.
If ListBox1.Items(e.Index).ToString() = "red.txt" Then
e.Graphics.FillRectangle(Brushes.red, e.Bounds)
End If
e.Graphics.DrawString(ListBox1.Items(e.Index).ToString(), e.Font, Brushes.Black, New System.Drawing.PointF(e.Bounds.X, e.Bounds.Y))
e.DrawFocusRectangle()
推荐答案
处理DrawItem事件并自己绘制每个项目.您必须具有 ListBox1.DrawMode = DrawMode.OwnerDrawFixed
Handle the DrawItem event and paint each item yourself. You must have ListBox1.DrawMode = DrawMode.OwnerDrawFixed
Private Sub ListBox1_DrawItem(sender As Object, e As DrawItemEventArgs) Handles ListBox1.DrawItem
Dim s As ListBox = CType(sender, ListBox)
If e.Index < 0 Then Exit Sub
Dim t = s.Items(e.Index).ToString()
Using g = e.Graphics
e.DrawBackground()
If t.Contains("*"c) Then ' your custom condition
g.FillRectangle(New SolidBrush(Color.Red), e.Bounds)
End If
g.DrawString(t, e.Font, New SolidBrush(e.ForeColor), New Point(e.Bounds.X, e.Bounds.Y))
e.DrawFocusRectangle()
End Using
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.DrawMode = DrawMode.OwnerDrawFixed
End Sub
这篇关于使用VIsual Basic 2015动态更改列表框行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!