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()))
{
}
}
}
But I don't know which method to use in order to change the appearance of a ListBox
row. Can anybody help me?
**EDIT: **
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();
}
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…