views:

61

answers:

2

I've got a DataTable with this fields

datatable.Columns.Add("ProductID", typeof(int));
datatable.Columns.Add("LocationList", typeof(List<string>));
datatable.Columns.Add("LocationIds", typeof(List<int>));
datatable.Columns.Add("ProductName", typeof(string));
datatable.Columns.Add("Brand", typeof(string));
datatable.Columns.Add("Price", typeof(decimal));
datatable.Columns.Add("Quantity", typeof(int));
datatable.Columns.Add("Locations", typeof(string));

And I bind it to a ListView

foreach (DataRow row in productsDataTable.Rows)
{
    var item = new ListViewItem(row[0].ToString());
    for (var i = 1; i < productsDataTable.Columns.Count; i++)
        item.SubItems.Add(row[i].ToString());

    lvSearchResults.Items.Add(item);
}

I want to bind the List<> fields, so that when a row is selected, I'd be able to get the data from the Lists and do some calculations with it. Is there any way to do this?

+1  A: 

The ListViewItem.Tag property allows you to associate anything you want with the item. You could store the entire DataRow in there and retrieve any columns you want.

Evgeny
+1  A: 

The ListViewItem has a Tag property that you can store data in to retrieve and use later, for example:

foreach (DataRow row in productsDataTable.Rows)
{
    var item = new ListViewItem(row[0].ToString());

    // Store the specific values you want to later retrieve
    item.Tag = new object[] { row["LocationList"], row["LocationIds"] };

    // Or, store the whole row
    item.Tag = row;

    lvSearchResults.Items.Add(item);
}
Rob
How do I retrieve the data from the Tag property?
Ivan Stoyanov
@Ivan, if you've got a reference to the specific `ListViewItem` you care about, you can just access its `Tag` property to obtain the data =)
Rob
Might I suggest instead of `new object[] { ... }` to use `Tuple.Create()` instead to maintain strong typing? Even better, of course, declare a tiny class of your own with a meaningful name and just those two fields.
Timwi
@Timwi, no point over-complicating things when giving an example of how to do something, Tuple isn't available from 1.1 onwards (and in the absence of information to the contrary, I try to not assume that the OP is on 4.0), and declaring a tiny class would have nearly doubled the size of my code sample (excluding blank lines) =) Worthwhile added commentary though.
Rob