SIGN UP MEMBER LOGIN:    
ARTICLE

Working with ListView in C#

Posted by Mahesh Chand Articles | Windows Controls C# December 26, 2010
A ListView control provides an interface to display a list of items using different views including text, small images, and large images. In this tutorial, we will learn how to work with the Windows Forms ListView control using C#.
Reader Level:
Download Files:
 

ListView in C#

A ListView control provides an interface to display a list of items using different views including text, small images, and large images.

In this tutorial, we will learn how to create a ListView control. We will also see how to create multiple views of ListView items. This article also covers most of the properties and methods of the ListView control. 

Creating a ListView

There are two approaches to create a ListView control in Windows Forms. Either we can use the Forms designer to create a control at design-time or we can use the ListView class to create a control at run-time.

Design-time

In our first approach, we are going to create a ListView control at design-time using the Forms designer.

To create a ListView control at design-time, we simply drag and drop a ListView control from Toolbox onto a Form in Visual Studio. After you drag and drop a ListView onto a Form, the ListView looks like Figure 1. Once a ListView is on the Form, you can move it around and resize it using mouse and set its properties and events.

ListViewImg1.jpg

Figure 1

Run-time

The ListView class represents a ListView control in Windows Forms. To create a ListView control at run-time, we create an instance of the ListView class, set its properties and add ListView object to the Form controls.

First step to create a dynamic ListView is to create an instance of ListView class. The following code snippet creates a ListView control object.

ListView ListView1 = new ListView();

In the next step, you may set properties of a ListView control. The following code snippet sets location, width, height, background color, foreground color, Text, Name, and Font properties of a ListView.

ListView1.Location = new System.Drawing.Point(12, 12);
ListView1.Name = "ListView1";
ListView1.Size = new System.Drawing.Size(245, 200);
ListView1.BackColor = System.Drawing.Color.Orange;
ListView1.ForeColor = System.Drawing.Color.Black;

Once the ListView control is ready with its properties, the next step is to add the ListView to a Form. To do so, we use Form.Controls.Add method that adds ListView control to the Form controls and displays on the Form based on the location and size of the control. The following code snippet adds a ListView control to the current Form.

Controls.Add(ListView1);

Setting ListView Properties

The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure 2.

ListViewImg2.jpg

Figure 2

Name

Name property represents a unique name of a ListView control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a ListView control.

ListView1.Name = "ListView1";

Location, Height, Width and Size

The Location property takes a Point that specifies the starting position of the ListView on a Form. You may also use Left and Top properties to specify the location of a control from the left top corner of the Form.  The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a ListView control.

ListView1.Location = new System.Drawing.Point(12, 12);
ListView1.Size = new System.Drawing.Size(245, 200);

Font

Font property represents the font of text of a ListView control. If you click on the Font property in Properties window, you will see Font name, size and other font options. The following code snippet sets Font property at run-time.

ListView1.Font = new Font("Georgia", 16);

Background and Foreground

BackColor and ForeColor properties are used to set background and foreground color of a ListView respectively. If you click on these properties in Properties window, the Color Dialog pops up.

Alternatively, you can set background and foreground colors at run-time. The following code snippet sets BackColor and ForeColor properties.

ListView1.BackColor = System.Drawing.Color.Orange;
ListView1.ForeColor = System.Drawing.Color.Black;

The new ListView with background and foreground looks like Figure 3.

 

ListViewImg3.jpg

Figure 3

You can also set borders style of a ListView by using the BorderStyle property. The BorderStyle property is represented by a BorderStyle enumeration that has three values – FixedSingle, Fixed3D, and None.  The default value of border style is Fixed3D. The following code snippet sets the border style of a ListView to FixedSingle.

ListView1.BorderStyle = BorderStyle.FixedSingle;

ListView Items

The Items property is used to add and work with items in a ListView. We can add items to a ListView at design-time from Properties Window by clicking on Items Collection as you can see in Figure 4.

ListViewImg4.jpg

Figure 4

When you click on the Collections, the ListView Collection Editor window will pop up where you can type strings. Each line added to this collection will become a ListView item. I add four items as you can see from Figure 5.

 

ListViewImg5.jpg

Figure 5

The ListView looks like Figure 6.

ListViewImg6.jpg

Figure 6

You can add same items at run-time by using the following code snippet.

ListView1.Items.Add("Mahesh Chand");
ListView1.Items.Add("Mike Gold");
ListView1.Items.Add("Praveen Kumar");
ListView1.Items.Add("Raj Beniwal");

Getting All Items

To get all items, we use the Items property and loop through it to read all the items.  The following code snippet loops through all items and adds item contents to a StringBuilder and displays in a MessageBox.

private void GetItemsButton_Click(object sender, EventArgs e)
{

    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    foreach (object item in ListView1.Items)
    {
        sb.Append(item.ToString());
        sb.Append(" ");
    }
    MessageBox.Show(sb.ToString());
}

Selected Text and Item

Text property is used to set and get text of a ListView. The following code snippet sets and gets current text of a ListView.

MessageBox.Show(ListView1.Text);

We can also get text associated with currently selected item by using Items property.

string selectedItem = ListView1.Items[ListView1.SelectedIndex].ToString();

Why the value of ListView.SelectedText is Empty?

SelectedText property gets and sets the selected text in a ListView only when a ListView has focus on it. If the focus moves away from a ListView, the value of SelectedText will be an empty string. To get current text in a ListView when it does not have focus, use Text property.

Selection Mode and Selecting Items

SelectionMode property defines how items are selected in a ListView. The SelectionMode value can be one of the following four SelectionMode enumeration values.

  • None - No item can be selected.
  • One - Only one item can be selected.
  • MultiSimple - Multiple items can be selected.
  • MultiExtended - Multiple items can be selected, and the user can use the SHIFT, CTRL, and arrow keys to make selections.

To select an item in a ListView, we can use the SetSelect method that takes item index and a true or false value where true value represent the item to be selected.

The following code snippet make a ListView multiple selection and selects second and third item in the list.

ListView1.SelectionMode = SelectionMode.MultiSimple;
ListView1.SetSelected(1, true);
ListView1.SetSelected(2, true);

We can clear all selected items by calling ClearSelected method.

ListView1.ClearSelected();

How to disable item selection in a ListView?

Just set SelectionMode property to None.

Sorting Items

The Sorted property set to true, the ListView items are sorted. The following code snippet sorts the ListView items.

ListView1.Sorted = true;

Find Items

The FindString method is used to find a string or substring in a ListView. The following code snippet finds a string in a ListView and selects it if found.

private void FindItemButton_Click(object sender, EventArgs e)
{

    ListView1.ClearSelected();
    int index = ListView1.FindString(textBox1.Text);
    if (index < 0)
    {
        MessageBox.Show("Item not found.");
        textBox1.Text = String.Empty;
    }
    else
   
{
        ListView1.SelectedIndex = index;
    }
}

 

ListView SelectedIndexChanged Event Hander

SelectedIndexChanged event is fired when the item selection is changed in a ListView. You can add the event handler using the Properties Widow and selecting on Event icon and double click on SelectedIndexChanged as you can see in Figure 7.

ListViewImg7.jpg

Figure 7

The following code snippet defines and implements these events and their respective event handlers. You can use this same code to implement event at run-time.

ListView1.SelectedIndexChanged += new EventHandler(ListView1_SelectedIndexChanged);
private
void ListView1_SelectedIndexChanged(object sender, System.EventArgs e)
{
    MessageBox.Show(ListView1.SelectedItem.ToString());
}

Now every time you change the selection in the ListView, you will see the selected item displayed in a MessageBox.

Data Binding

DataSource property is used to bind a collection of items to a ListView. The following code snippet is a simple data binding example where an ArrayList is bound to a ListView.

private void DataBindingButton_Click(object sender, EventArgs e)
{

    ArrayList authors = new ArrayList();
    authors.Add("Mahesh Chand");
    authors.Add("Mike Gold");
    authors.Add("Raj Kumar");
    authors.Add("Praveen Kumar");
    ListView1.Items.Clear();
    ListView1.DataSource = authors;
}

If you are binding an object with multiple properites, you must specify which property you are displaying by using the DisplayMember property.

ListView1.DataSource = GetData();
ListView1.DisplayMember = "Name";

 

Summary

In this article, we discussed discuss how to create a ListView control in Windows Forms. After that, we saw how to use various properties and methods. I am planning to extend this article to add more topics including multiple columns, multiple views, header with images and so on.

Further Readings

Here are some more articles and tutorials in ListView that you may want to read.

 

 

 

erver'>
Login to add your contents and source code to this article
share this article :
post comment
 

I want to create a chart(pie or bar)in silverlight using wcf.Am using telerik controls with oracle database.I need to bind data from db to chart.In Declarative approach i dont have any problem..please send code as soon as possible with screenshots.

Posted by pradeep kumar Jan 12, 2011

I understand that "authors" is the datasource. But i can't set the datasource, i only have the choise off databindings. I working with an ArrayList.

Posted by michael depoorter Jan 05, 2011

This is just an example where "authors" is the data source. You can set this as any data source you have in your code. For example, if you have a DataSet or DataTable, you can set that as data source instead of "authors".

Posted by Mahesh Chand Jan 05, 2011

I read your article, but i don't understand this "ListView1.DataSource = authors;". When i try this, i don't have the possibility to choise for datasource. I only can choose "DataBindings". Can somebody tell me why?

Posted by michael depoorter Jan 05, 2011

It is a very nice article mahesh. More people will get benifit out of it. Further Readings section is real nice idea. Thanks for sharing.

Posted by Sivaraman Dhamodaran Dec 28, 2010
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Nevron Gauge for SharePoint
Become a Sponsor