我正在尝试更改 ListBox
中一些行的背景颜色。我有两个列表,一个显示为 ListBox
中的名称列表,另一个具有与第一个列表相似的某些值。当单击按钮时,我想搜索 ListBox
和第二个列表,并更改 ListBox
中那些出现在第二个列表中的值的颜色。我的 ListBox 搜索如下:
for (int i = 0; i < listBox1.Items.Count; i++)
{
for (int j = 0; j < students.Count; j++)
{
if (listBox1.Items[i].ToString().Contains(students[j].ToString()))
{
}
}
}
但我不知道该使用哪种方法来改变 ListBox
行的外观。有人能帮帮我吗?
**编辑:**
嗨,我将我的代码编写如下:
private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
Graphics g = e.Graphics;
Brush myBrush = Brushes.Black;
Brush myBrush2 = Brushes.Red;
g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds);
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
for (int i = 0; i < listBox1.Items.Count; i++)
{
for (int j = 0; j < existingStudents.Count; j++)
{
if (listBox1.Items[i].ToString().Contains(existingStudents[j]))
{
e.Graphics.DrawString(listBox1.Items[i].ToString(),
e.Font, myBrush2, e.Bounds, StringFormat.GenericDefault);
}
}
}
e.DrawFocusRectangle();
}
现在它把我的List
画在ListBox
中,但是当我第一次点击按钮时,它只以红色显示在List
中的学生,当我点击ListBox
时,它则绘制所有元素。我希望它能够显示所有元素,并且当我点击按钮时,它会将所有元素和在List
中找到的元素以红色显示。我哪里错了?