C#:改变列表框的行颜色?

时间:2010-03-31 16:18:37

标签: c# listbox

我正在尝试更改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中的红色元素。我的错误在哪里?

7 个答案:

答案 0 :(得分:27)

我找到解决方案而不是使用ListBox我使用ListView.It允许更改列表项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;
            }
        }
    }
}

答案 1 :(得分:22)

您需要自己绘制项目。将DrawMode更改为OwnerDrawFixed并处理DrawItem事件。

/// <summary>
/// Handles the DrawItem event of the listBox1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.DrawItemEventArgs"/> instance containing the event data.</param>
private void listBox1_DrawItem( object sender, DrawItemEventArgs e )
{
   e.DrawBackground();
   Graphics g = e.Graphics;

    // draw the background color you want
    // mine is set to olive, change it to whatever you want
    g.FillRectangle( new SolidBrush( Color.Olive), e.Bounds );

    // draw the text of the list item, not doing this will only show
    // the background color
    // you will need to get the text of item to display
    g.DrawString( THE_LIST_ITEM_TEXT , e.Font, new SolidBrush( e.ForeColor ), new PointF( e.Bounds.X, e.Bounds.Y) );

    e.DrawFocusRectangle();
}

答案 2 :(得分:13)

首先使用此命名空间:

using System.Drawing;

在表单的任何位置添加:

listBox.DrawMode = DrawMode.OwnerDrawFixed;
listBox.DrawItem += listBox_DrawItem;

这是事件处理程序:

private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
     e.DrawBackground();

     Graphics g = e.Graphics;
     g.FillRectangle(new SolidBrush(Color.White), e.Bounds);
     ListBox lb = (ListBox)sender;
     g.DrawString(lb.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), new PointF(e.Bounds.X, e.Bounds.Y));

     e.DrawFocusRectangle();
}

答案 3 :(得分:2)

我认为你必须自己绘制列表项目来实现这一点。

Here's a post提出同样的问题。

答案 4 :(得分:1)

将列表框项添加到窗体后,请在属性面板中使用 OwnerDrawFixed 选项更改 DrawMode 。如果您忘记这样做,则以下任何代码均无效。然后从事件区域中单击 DrawItem 事件。

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
   // 1. Get the item
   string selectedItem = listBox1.Items[e.Index].ToString();
                    
   // 2. Choose font 
   Font font = new Font("Arial", 12);
        
   // 3. Choose colour
   SolidBrush solidBrush = new SolidBrush(Color.Red);
        
   // 4. Get bounds
   int left = e.Bounds.Left;
   int top = e.Bounds.Top;
                    
   // 5. Use Draw the background within the bounds
   e.DrawBackground();
        
   // 6. Colorize listbox items
   e.Graphics.DrawString(selectedItem, font, solidBrush, left, top);
}

答案 5 :(得分:0)

我找到了将列表框项目的背景变为黄色的解决方案。我尝试了以下解决方案来实现输出。

 for (int i = 0; i < lstEquipmentItem.Items.Count; i++)
                {
                    if ((bool)ds.Tables[0].Rows[i]["Valid_Equipment"] == false)
                    {
                        lblTKMWarning.Text = "Invalid Equipment & Serial Numbers are highlited.";
                        lblTKMWarning.ForeColor = System.Drawing.Color.Red;
                        lstEquipmentItem.Items[i].Attributes.Add("style", "background-color:Yellow");
                        Count++;
                    }

                }

答案 6 :(得分:-4)

怎么样

      MyLB is a listbox

        Label ll = new Label();
        ll.Width = MyLB.Width;
        ll.Content = ss;
        if(///<some condition>///)
            ll.Background = Brushes.LightGreen;
        else
            ll.Background = Brushes.LightPink;
        MyLB.Items.Add(ll);