简体   繁体   中英

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. 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

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. Listview is not an option for me.

You need to handle the DrawItem event of the ListBox to draw the Items with specified color

Note : here in below code i'm changing the colour of the ListBox item with Green

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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