We may want to change the color of list box individual items.
For example First Line in Blue Color, Second line in Green, Third line in Black etc
with standard listboxes, all items have same settings, thus you would need to find alternative way.
Here's the Solution:
We have to write own handler for the listbox's DrawItem event.
Steps to do:
Drag and drop a standard ListBox to your .NET WinForm.
Set the ListBox's DrawMode property:
Drag and drop a button
Write the handler for Button Click to populate list box
Write the handler for the DrawItem event:
public Form1()
{
InitializeComponent();
'Set the drawmode property
listBox1.DrawMode = DrawMode.OwnerDrawFixed;
}
private void btnPopulateListbox_Click(object sender, EventArgs e)
{
//Add items
this.listBox1.Items.Add("A");
this.listBox1.Items.Add("B");
this.listBox1.Items.Add("C");
this.listBox1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.listBox1_DrawItem);
}
//Event Handler to change the colour in the list box item
private void listBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
// Draw the background of the ListBox control for each item.
// Create a new Brush and initialize to a Black colored brush
// by default.
e.DrawBackground();
Brush myBrush = Brushes.Black;
// Determine the color of the brush to draw each item based on
// the index of the item to draw.
switch (e.Index)
{
case 0:
myBrush = Brushes.Blue; //First Row Blue Colour
break;
case 1:
myBrush = Brushes.Green; //Second Row Green Colour
break;
case 2:
myBrush = Brushes.Black; //Third Row Black Colour
break;
}
// Draw the current item text based on the current
// Font and the custom brush settings.
//
e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(),
e.Font, myBrush,e.Bounds,StringFormat.GenericDefault);
// If the ListBox has focus, draw a focus rectangle
// around the selected item.
e.DrawFocusRectangle();
}
for more details http://www.thescarms.com/dotnet/CustomListBox.aspx
No comments:
Post a Comment