Winforms - How to alternate the color of strings in a ListView control?

Using C # Winforms (3.5).

Is it possible to set the colors of the lines for automatic rotation in the list?

Or do I need to manually set the color of the line every time a new line is added to the list?

Based on the MSDN article, a manual method would look like this:

//alternate row color if (i % 2 == 0) { lvi.BackColor = Color.LightBlue; } else { lvi.BackColor = Color.Beige; } 
+4
source share
6 answers

I am afraid that this is the only way in Winforms. XAML allows this to be used in styles.

+5
source

Set the ListView OwnerDraw property to true, and then execute the DrawItem handler:

  private void listView_DrawItem(object sender, DrawListViewItemEventArgs e) { e.DrawDefault = true; if ((e.ItemIndex%2) == 1) { e.Item.BackColor = Color.FromArgb(230, 230, 255); e.Item.UseItemStyleForSubItems = true; } } 

This example is simple, you can improve it.

+1
source

As far as I know, WPF allows you to set the style for any control using <Styles/> But in winforms I am afraid that this is the only way.

0
source

You can also use the owner’s drawing, rather than setting properties explicitly. Owner pattern is less vulnerable to reordering items.

Here's how to do it in Better ListView (a third-party component that offers both free and advanced versions) - it's just a matter of handling the DrawItemBackground event:

 private void ListViewOnDrawItemBackground(object sender, BetterListViewDrawItemBackgroundEventArgs eventArgs) { if ((eventArgs.Item.Index & 1) == 1) { eventArgs.Graphics.FillRectangle(Brushes.AliceBlue, eventArgs.ItemBounds.BoundsOuter); } } 

result:

enter image description here

0
source

Set the ListView OwnerDraw property to true, and then execute the DrawItem handler. Take a look here: Winforms - How do I alternate the color of rows in a ListView control?

0
source
  for (int i = 0; i <= listView.Items.Count - 1; i = (i + 2)) { listView.Items[i].BackColor = Color.Gainsboro; } 

Set the main background in the properties menu, then use this code to set an alternate color.

0
source

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


All Articles