How to Add Shaded Rows to ListView’s Details View


Sometimes it can be challenging to read the Details view in a ListView, especially if the rows are long. This article shows how to add shading to every second row to make a ListView easier to read.

As you may know, you can alter the appearance of individual ListViewItem’s such as the Font and BackColor. But these values are ignored unless you set the item’s UseItemStyleForSubItems property to true.

The following code demonstrates how to shade every other row in a ListView:

ListView listView = this.ListView_Products;

listView.View = View.Details;

int i = 0;

Color shaded = Color.FromArgb( 240, 240, 240 );

foreach (Product product in products)

{

ListViewItem item = new ListViewItem( product.Name );

item.SubItems.Add( product.Version );

item.SubItems.Add( product.Description );

item.SubItems.Add( product.Status );

if (i++ % 2 == 1)

 {

item.BackColor = shaded;

item.UseItemStyleForSubItems = true;

}

listView.Items.Add( item );

}


VB .NET Code:-

Dim listView As ListView = Me.ListView_Products

listView.View = View.Details

Dim i As Integer = 0

Dim shaded As Color = Color.FromArgb(240, 240, 240)

For Each product As Product In products

    Dim item As New ListViewItem(product.Name)

    item.SubItems.Add(product.Version)

    item.SubItems.Add(product.Description)

    item.SubItems.Add(product.Status)

    If System.Math.Max(System.Threading.Interlocked.Increment(i),i – 1) Mod 2 = 1 Then

        item.BackColor = shaded

        item.UseItemStyleForSubItems = True

    End If

    listView.Items.Add(item)

Next

Advertisements

Author: Imran Akram

A .NET/SharePoint Consultant and a political enthusiast who believes in putting the feet of the elected and/or unelected officials to fire in order to get good governance.

2 thoughts on “How to Add Shaded Rows to ListView’s Details View”

  1. i m new to dot net. Can u please me what u mean

    For Each product As Product In products.Is product a class or a table from the data base?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s