How to change the color of a selected item in a ListBox?

I have a ListBox control with some elements and I want to change the color of the selected element ... How to do this in C # (WinForms)? Help me please:)

+3
source share
3 answers

Here's how you can set, say, red, to selected ASP.NET ListBox items:

<asp:ListBox runat="server" ID="ListBox1"> <asp:ListItem Text="Text1"></asp:ListItem> <asp:ListItem Text="Text2"></asp:ListItem> </asp:ListBox> if(ListBox1.SelectedItem != null) ListBox1.SelectedItem.Attributes["style"] = "color:red"; 
+2
source

A good example of this is available here.

I am copying the code from the above example:

"You can set the color of individual elements in a ListBox using C # in your .NET WinForm by writing your own handler for the listbox DrawItem .

Set the DrawBox DrawMode property:

Add a standard ListBox to your .NET WinForm, then set its DrawMode property to OwnerDrawFixed , which causes the ListBox DrawItem event to fire.

Write a DrawItem event handler:

 private void lstBox_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.Red; break; case 1: myBrush = Brushes.Orange; break; case 2: myBrush = Brushes.Purple; 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(); } 

In the InitializeComponent section, DrawItem handler to the DrawItem event:

 this.lstBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.lstBox_DrawItem); 
+1
source

You can try combinations of different brushes and colors.

using System.Drawing; using System.Drawing.Drawing2D;

  private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { Rectangle rc = listBox1.GetItemRectangle(listBox1.SelectedIndex); LinearGradientBrush brush = new LinearGradientBrush( rc, Color.Transparent, Color.Red, LinearGradientMode.ForwardDiagonal); Graphics g = Graphics.FromHwnd(listBox1.Handle); g.FillRectangle(brush, rc); } 
0
source

Source: https://habr.com/ru/post/1487884/


All Articles