问题描述
我试图改变一些行的背景颜色在的ListBox
。我有一个人的名字,并显示在一个的ListBox
两个列表。第二个列表有一些类似的值作为第一个列表
。当点击一个按钮,我想搜索的ListBox
第二列表
,并更改<$的颜色C $ C>的ListBox 对于那些出现在列表
值。我在 ListBox中搜索
如下:
I am trying to change the background color of some rows in a ListBox
. I have two lists that one has names and is displayed in a ListBox
. The second list has some similar values as the first List
. When clicking a button, I want to search the ListBox
and the second List
, and change the color of the ListBox
for those values that appear in the List
. My search in the ListBox
is as follows:
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
行的外观使用的方法。任何人可以帮助我吗?
But I don't know which method to use in order to change the appearance of a ListBox
row. Can anybody help me?
**编辑:**
您好,我写我的code如下:
HI I wrote my code as follows:
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();
}
现在它吸引我的列表
在的ListBox
,但是当我第一次按一下按钮,它显示为红色只有那些在列表
,当我点击的ListBox
它绘制所有元素的学生。我想,它会显示所有的元素,当我按一下按钮,它会显示所有元素,并在列表
红色中发现的元素。哪里是我的错?
Now it draws my List
in the ListBox
, but when I click the button first, it shows in red only the students that are in the List
and when I click on the ListBox
it draws all the elements. I want that it will show all the elements , and when I click the button it will show all the elements and the element found in the List
in red. Where is my mistake?
推荐答案
我找到解决方案,而不是使用的ListBox我用ListView.It允许改变列表项背景色。
I find solution that instead of using ListBox I used ListView.It allows to change list items 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#:更改列表框行的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!