C#:更改列表框的行颜色?
我正在尝试更改中某些行的背景颜色ListBox。我有两个列表,一个带有名称,并显示在中ListBox。第二个列表具有与第一个相似的值List。单击按钮时,我要搜索ListBox和List,然后更改的颜色,以ListBox显示的值List。我在中的搜索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以红色显示的元素。我的错误在哪里?
回答:
我找到的解决方案不是使用ListBox,而是使用ListView,它允许更改列表项BackColor。
private void listView1_Refresh(){
for (int i = 0; i < listView1.Items.Count; i++)
{
listView1.Items[i].BackColor = Color.Red;
for (int j = 0; j < existingStudents.Count; j++)
{
if (listView1.Items[i].ToString().Contains(existingStudents[j]))
{
listView1.Items[i].BackColor = Color.Green;
}
}
}
}
以上是 C#:更改列表框的行颜色? 的全部内容, 来源链接: utcz.com/qa/398066.html

