1. Computing

C# Programming Tutorial - Programming Advanced Winforms in C#

By

3 of 10

Working with ListViews in C# Winforms
The sample ListView and controls

This is a handy control for displaying tabular data without the complexity of a grid. You can display items as large or small icons, as a list of icons in a vertical list or most usefully as a list of items and subitems in a grid and that's what we'll do here.

After dropping a ListView on a form click the columns property and add 4 columns. These will be TownName, X, Y and Pop. Set the text for each ColumnHeader. If you can't see the headings on the ListView (after you've added all 4), set the ListView's View Property to Details. If you view the code for this example then browse down to where it says Windows Form Designer code and expand the region you see the code that creates the ListView. It's useful to see how the system works and you can copy this code and use it yourself.

You can set the width for each column manually by moving the cursor over the header and dragging it. Or you can do it in the code visible after you expanded the form designer region. You should see code like this:

this.Population.Text = "Population";
this.Population.Width = 77;

For the population column, Changes in the code are reflected in the designer and vice versa. Note that even if you set the Locked property to true this only affects the designer and at run-time you can resize columns.

ListViews also come with a number of dynamic properties. Click the (Dynamic Properties) and tick the property you want. When you set a property to be dynamic, it creates an XML .config file and adds it to Solution Explorer.

Making changes at design time is one thing but we really need to do it when the program is running. A ListView is made up of 0 or more items. Each item (a ListViewItem) has a text property and a SubItems collection. The first column displays the Item text, the next column displays SubItem[0].text then SubItem[1].text and so on.

I've added a button to add a row and an edit box for the Town Name. Enter any name in the box and click Add Row. This adds a new row to the ListView with the town name put in the first column and the next three columns (SubItems[0..2] ) are populated with random numbers (converted to strings) by adding those strings to them.

Random R= new Random() ;
ListViewItem LVI = list.Items.Add(tbName.Text) ;
LVI.SubItems.Add( R.Next(100).ToString()) ; // 0..99
LVI.SubItems.Add( R.Next(100).ToString()) ;
LVI.SubItems.Add((( 10+R.Next(10))*50).ToString());

On the next page : Updating a ListView

  1. About.com
  2. Computing
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Working with ListViews in C# Winforms

©2014 About.com. All rights reserved.