C#:更改列表框行颜色? [英] C# : changing listbox row color?

查看:23
本文介绍了C#:更改列表框行颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改 ListBox 中某些行的背景颜色.我有两个列表,其中一个具有名称并显示在 ListBox 中.第二个列表与第一个 List 有一些相似的值.单击按钮时,我想搜索 ListBox 和第二个 List,并更改 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?

****

您好,我的代码如下:

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 中绘制了我的 List,但是当我首先单击按钮时,它仅以红色显示 List<中的学生/code> 当我点击 ListBox 时,它会绘制所有元素.我希望它会显示所有元素,当我单击按钮时,它将以红色显示 List 中的所有元素和元素.我的错在哪里?

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.它允许更改列表项 BackColor.

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#:更改列表框行颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆