Select full rows in a ListView and store extra information with ListView rows in C#

example

This program displays lists several books in a ListView control. It lists the book’s title, web page, page count, and year published.

In addition, the program stores each book’s International Standard Book Number (ISBN), but it doesn’t list that information in the ListView.

Normally when a ListView is displaying its Details view, the user must click on the leftmost column to select an entry, and then the control only highlights that column. In this program, when the user clicks any column in the ListView, the control highlights the entire row. To do that, the code simply sets the ListView control’s FullRowSelect property to true. (You can also set this property at design time.)

// Select whole rows.
lvwBooks.FullRowSelect = true;

When you add an item to the ListView‘s Items collection, the Add method returns a ListViewItem representing the new row. You can save extra information in that object’s Tag property. (Note that many objects, including all controls, have a Tag property where you can store extra information.)

The following code shows how the program creates its first ListView item.

ListViewItem new_item;
new_item = lvwBooks.Items.Add(new ListViewItem(new string[]
    {   "C# 5.0 Programmer's Reference",
        "http://www.wrox.com/WileyCDA/...", 
        "960", "2014"},
    csharp_group));
new_item.Tag = "1118847288";

When the user double-clicks on the control, the following code display the corresponding web page at Amazon.

// Open the Amazon page for the selected book.
private void lvwBooks_DoubleClick(object sender, EventArgs e)
{
    if (lvwBooks.SelectedItems.Count < 1) return;

    // Get the selected item.
    ListViewItem selected_item =
        lvwBooks.SelectedItems[0];

    // Use the Tag value to build the URL.
    string url = "http://www.amazon.com/gp/product/@ISBN@";
    url = url.Replace("@ISBN@", (string)selected_item.Tag);

    // Open the URL.
    System.Diagnostics.Process.Start(url);
}

This code gets the ListView‘s selected row. It gets the row’s Tag property and uses it to build an Amazon URL. The program then uses System.Diagnostics.Process.Start to open the URL in the system’s default browser.


Download Example   Follow me on Twitter   RSS feed


This entry was posted in controls, user interface and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *