简体   繁体   English

如何根据其索引更改列表框项目颜色c#

[英]how to change listbox item color c# based on its index

I want to change the color of a ListBox item based on it's index. 我想根据其索引更改ListBox项目的颜色。 I have a TextBox...and when the user enters an index number I want to change the text color of the corresponding index in the list box 我有一个TextBox ...并且当用户输入索引号时,我想更改列表框中相应索引的文本颜色

eg: When the user clicks a button some thing like this happen: 例如:当用户单击按钮时,会发生类似以下情况:

    private void button1_Click(object sender, EventArgs e)
            {
                setcolor(int.Parse(textBox1.Text));
            }

and I want to create such setcolor function. 我想创建这样的setcolor函数。 Listview is not an option for me. Listview不是我的选择。

You need to handle the DrawItem event of the ListBox to draw the Items with specified color 您需要处理ListBoxDrawItem事件以绘制具有指定color的Items

Note : here in below code i'm changing the colour of the ListBox item with Green 注意:在下面的代码中,我正在用Green更改ListBox项的颜色

Try This: 尝试这个:

int itemIndex = -1;
public Form1()
{
  InitializeComponent();
  this.listBox1.DrawItem += new            
          System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem);
}

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    Graphics g = e.Graphics;
    if(e.Index == itemIndex )
    {
        g.FillRectangle(new SolidBrush(Color.Green), e.Bounds);
    }
    else
    {
        g.FillRectangle(new SolidBrush(Color.White), e.Bounds);
    }
    ListBox lb = (ListBox)sender;
    g.DrawString(listBox1.Items[e.Index].ToString(), e.Font,
          new SolidBrush(Color.Black), new PointF(e.Bounds.X, e.Bounds.Y));
    e.DrawFocusRectangle();
}

private void button1_Click(object sender, EventArgs e)
{
    setcolor(int.Parse(textBox1.Text));
}

void setcolor(int index)
{ 
    itemIndex = index;
    listBox1.DrawMode = DrawMode.Normal;
    listBox1.DrawMode = DrawMode.OwnerDrawFixed;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM