Click here to Skip to main content
15,891,904 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i m using a listbox control on my windows application , i want to set a alternate backcolor on listbox items , i have tried...
C#
private void listBox2_DrawItem(object sender, DrawItemEventArgs e)
       {
           //bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);


           int index = e.Index;
           if (index >= 0 && index < listBox2.Items.Count)
           {

               Graphics g = e.Graphics;
               Color color;


                   if (index % 2 == 0)
                   {
                       color = Color.Gray;
                   }
                   else
                   {
                       color = Color.White;
                   }

               /* Draw Background */
               g.FillRectangle(new SolidBrush(color), e.Bounds);

               /* Draw Item Text */
               g.DrawString(listBox2.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), e.Bounds, StringFormat.GenericDefault);

           }
           e.DrawFocusRectangle();
       }


and i see no effect on listbox with this code:
what else i m missing...
Posted
Updated 16-Jun-22 21:26pm
Comments
johannesnestler 15-Mar-12 9:04am    
Is it possible for you to use a ListView - would be better - same functionality but control over the items...
johannesnestler 15-Mar-12 9:06am    
Ah - now I see - for getting your code to work you have to sub-class ListBox and overwrite DrawItem

try this:
 you have to chagne listbox DrawMode property like below

//this.DrawMode = DrawMode.OwnerDrawFixed;

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            var item = listBox1.Items[e.Index] as ColoredItem;

            Graphics g = e.Graphics;
            g.FillRectangle(new SolidBrush(Color.LightCyan), e.Bounds);

            if (item != null)
            {
                e.Graphics.DrawString(
                    item.text,
                    e.Font,
                    new SolidBrush(item.color),
                    e.Bounds);
            }
        }
 
Share this answer
 
Try this:
C#
private static void recolorListItems(ListView lv) {
        for (int i = 0; i < lv.Items.Count; ++i)
         {
            var item = lv.Items[i];
            item.BackColor = (i % 2 == 0) ? Color.Gray : Color.White;
        }
    }
 
Share this answer
 
v2
Comments
choudhary.sumit 15-Mar-12 8:10am    
but i m using listbox not listview...:(

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900