[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.