Obadah Hammoud
Obadah Hammoud

Reputation: 572

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.

Upvotes: 0

Views: 951

Answers (1)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

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

Upvotes: 1

Related Questions