Ok, I am having more problems with my C# WPF ListView control. Here it is in all its glory:
<Window x:Class="ebook.SearchResults" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="ISBNListView" Height="503" Width="1004">
<Grid>
<ListView Name="listView1" Margin"22,30,33,28" MouseDoubleClick="getSelectedItem" >
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="ISBN" Width="150" DisplayMemberBinding="{Binding ISBN}"/>
<GridViewColumn Header="Title" Width="350" DisplayMemberBinding="{Binding Title}"/>
<GridViewColumn Header="Author" Width="350" DisplayMemberBinding="{Binding Author}" />
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
</Grid>
I am filling the listView with the following:
XDocument xdoc = XDocument.Load(GlobalVars.docPath + "\\tempSearchResults.xml");
var items = from item in xdoc.Descendants("Book")
select new
{
ISBN = item.Element("ISBN").Value,
Title = item.Element("Title").Value,
AuthTexts = item.Element("Author").Value
};
foreach (var item in items)
{
listView1.Items.Add(new { ISBN = item.ISBN, Title = item.Title, Author = item.AuthTexts });
}
I am having a devil of a time retrieving data from a row when it is double clicked. The DoubleClick does popup a message box with all the data in the row, I just cannot seem to get only one subitem or cell's data. Say a row has ISBN: 1234567 Title: Hurrr Author: Waldo, how do I just retrieve the ISBN or just the title?
private void getSelectedItem(object sender, MouseButtonEventArgs e)
{
System.Windows.MessageBox.Show(listView1.SelectedItems[0].ToString());
}
Still new to C# and .Net and banging my head against the wall. I figure this should be rather simple.
listView1.SelectedItems[0]
returns an object
. You first need to cast it to its specific type before you can access its members. For casting you need to know the name of the class to cast to, but you're adding instances of an anonymous class (= has no name) to your ListView.
Solution: Define a class (e.g., Book
) with ISBN, Title and Author properties and add instances of Book
to the ListView. Then you can do the necessary cast:
private void getSelectedItem(object sender, MouseButtonEventArgs e)
{
Book book = (Book)listView1.SelectedItems[0];
System.Windows.MessageBox.Show(book.ISBN);
}
Don't forget to add instances if Book
to the ListView instead of instances of an anonymous type:
var items = from item in xdoc.Descendants("Book")
select new Book // <---
{
ISBN = (string)item.Element("ISBN"),
Title = (string)item.Element("Title"),
Author = (string)item.Element("Author"),
};
foreach (var item in items)
{
listView1.Items.Add(item);
}