I have an asp:ListBox1
and two buttons. When I click on button 1, I add a text to ListBox1
.
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Add("Message1");
}
When I click on the second button, another thext is added to ListBox1
.
protected void Button2_Click(object sender, EventArgs e)
{
ListBox1.Items.Add("Message2");
}
The messages are correctly added. I want to change the background color for each row. For example, I want the row with "Message1" text to have a red background and the other row to have green background. How could I do this?
you can use this code for asp.net
protected void Button1_Click(object sender, EventArgs e)
{
ListItem message1 = new ListItem("Message1","Message1");
message1.Attributes.Add("style", "background-color: RED");
ListBox1.Items.Add(message1);
}
protected void Button2_Click(object sender, EventArgs e)
{
ListItem meassage2 = new ListItem("Message2","Message2");
message2.Attributes.Add("style", "background-color: GREEN");
ListBox1.Items.Add(message2);
}
private void InitializeListBox()
{
//ad mode to draw
ListBox1.DrawMode = DrawMode.OwnerDrawFixed;
ListBox1.DrawItem += new DrawItemEventHandler(ListBox1_DrawItem);
Controls.Add(ListBox1);
}
private void ListBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e){
// Draw the background of the ListBox control for each item.
e.DrawBackground();
// Define the default color of the brush as black.
Brush myBrush = Brushes.Black;
switch(ListBox1.Items[e.Index].ToString()){
case "Message1" : myBrush = Brushes.Red; break;
case "Message2" : myBrush = Brushes.Green;break;
}
// Draw the current item text based on the current Font
// and the custom brush settings.
e.Graphics.DrawString(ListBox1.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();
}
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.