Jerry
Jerry

Reputation: 1785

Can't get value from selected item in listview WPF

I have a form where user enters data about a new inventory item (id,title, price, date, ect..). Data entered is saved to a collection and then redisplayed in a listview.

I get a "Specified cast is not valid" pointing to "key = (int)lvwInventory.SelectedItems[0];" when trying to extract the selected value. I'm trying to get the ID out and use it to open an edit window for that item.

What am I doing wrong here?

list view in question

<ListView Height="249" HorizontalAlignment="Left" Margin="27,28,0,0" Name="lvwInventory" VerticalAlignment="Top" Width="384" ItemsSource="{Binding col}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Type" DisplayMemberBinding="{Binding Type}" />
            <GridViewColumn Header="Title" DisplayMemberBinding="{Binding Title}" />
            <GridViewColumn Header="Price" DisplayMemberBinding="{Binding Price}" />
            <GridViewColumn Header="Date Added" DisplayMemberBinding="{Binding Date}" />
        </GridView>
    </ListView.View>
</ListView>

stockobject class

public class StockObject
    {
        // create stock object properties
        public int ID { get; set; }
        public string Title { get; set; }
        public DateTime Date { get; set; }
        public double Price { get; set; }
        public char Type { get; set; }

Event that's trying to get value out of the selected item

private void btnViewItem_Click(object sender, RoutedEventArgs e)
    {
        int key;

        if (lvwInventory.SelectedIndex == -1) return;

        key = (int)lvwInventory.SelectedItems[0];

        StockObject s = col[key];
        bookDialog.View(s);
    }

Upvotes: 2

Views: 22029

Answers (3)

Nilesh Mohite
Nilesh Mohite

Reputation: 75

Here is the way i got it !

Get Listview Item

SearchedPurchases Purchase_Invoice = (SearchedPurchases)listView1.SelectedItems[0];
string PurchaseInvoice = Purchase_Invoice.InvoiceNo;

Upvotes: 1

Vlad
Vlad

Reputation: 35584

The thing is that your list view is bound against col, which happens to be a collection of StockObjects. So your SelectedItems[0] is a StockObject, not int.

Instead of

key = (int)lvwInventory.SelectedItems[0];
StockObject s = col[key];

you just need

StockObject s = (StockObject)lvwInventory.SelectedItems[0];

Maybe you want SelectedItem:

private void btnViewItem_Click(object sender, RoutedEventArgs e)
{
    StockObject s = lvwInventory.SelectedItem;
    if (s != null)
        bookDialog.View(s);
}

?

Upvotes: 2

BFree
BFree

Reputation: 103742

The selected item is the StockObject itself, which is why it won't let you cast it to an int. You need something like this:

var selectedStockObject = lvwInventory.SelectedItems[0] as StockObject;
if(selectedStockObject == null)
{
   return;
}

key = selectedStockObject.ID; //I'm assuming you want the ID as your key

Upvotes: 8

Related Questions