Let the user select full rows in a ListView and store extra information with ListView rows in C#

This program displays lists several books in a ListView. 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. Alternatively you can set this property at design time.

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

To save extra information with a row, note that the ListView control's Items collection's Add method returns a ListView item representing the new row. Simply save the 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.)

new_item = lvwBooks.Items.Add(new ListViewItem(new string[]
{ "Beginning Database Design Solutions",
"http://www.vb-helper.com/db_design.htm",
"552", "2008"},
general_group));
new_item.Tag = "9780470385494";

Finally, when the user double-clicks on the control, the following code finds the selected row, gets its 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.

// 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/exec/obidos/ASIN/@ISBN@/vbhelper/";
url = url.Replace("@ISBN@", (string)selected_item.Tag);

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

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.