Sample code to give alternate color for alternate items in listbox.
In my application lstBoxSelected is the name of listbox.
Write these two lines in page load event.
lstBoxSelected.DrawMode = DrawMode.OwnerDrawFixed;
lstBoxSelected.DrawItem += new DrawItemEventHandler(DrawListSelected);
DrawListSelected is the event for drawing backcolor for listitem.
private void DrawListSelected(object sender, DrawItemEventArgs e)
{
//Draw ListBox Items
Rectangle rect = new Rectangle();
rect = e.Bounds;
// Setup the stringformatting object
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
// Fill Backcolor for selected item
e.Graphics.FillRectangle(Brushes.Orange, e.Bounds);
}
else
{
Brush b; // Object used to define backcolor
b = Brushes.LightCyan;
if (e.Index % 2 == 0)
b = Brushes.PowderBlue;
else
b = Brushes.LightCyan;
e.Graphics.FillRectangle(b, rect);
}
if (lstBoxSelected.Items.Count > 0)
{
e.Graphics.DrawString(lstBoxSelected.Items[e.Index].ToString().Replace("*","").Trim(), e.Font, Brushes.Black, rect, sf);
}
}
In my application lstBoxSelected is the name of listbox.
Write these two lines in page load event.
lstBoxSelected.DrawMode = DrawMode.OwnerDrawFixed;
lstBoxSelected.DrawItem += new DrawItemEventHandler(DrawListSelected);
DrawListSelected is the event for drawing backcolor for listitem.
private void DrawListSelected(object sender, DrawItemEventArgs e)
{
//Draw ListBox Items
Rectangle rect = new Rectangle();
rect = e.Bounds;
// Setup the stringformatting object
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
// Fill Backcolor for selected item
e.Graphics.FillRectangle(Brushes.Orange, e.Bounds);
}
else
{
Brush b; // Object used to define backcolor
b = Brushes.LightCyan;
if (e.Index % 2 == 0)
b = Brushes.PowderBlue;
else
b = Brushes.LightCyan;
e.Graphics.FillRectangle(b, rect);
}
if (lstBoxSelected.Items.Count > 0)
{
e.Graphics.DrawString(lstBoxSelected.Items[e.Index].ToString().Replace("*","").Trim(), e.Font, Brushes.Black, rect, sf);
}
}
0 comments:
Post a Comment