Reputation: 325
I want to get SelectedItems
values in ListView` but it does not work!
I have no problem when selecting one item but I want to work in extended mode so it shows any of selected items.
my code is :
List<Fnamelist> familylist = new List<Fnamelist>();
public class Fnamelist
{
public Fnamelist(string fname)
{
this.Fname = fname;
}
private string fname = string.Empty;
public string Fname
{
get { return fname; }
set { fname = value; }
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(((Fnamelist)listView1.SelectedItems).Fname.ToString());
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
familylist.Add(new Fnamelist("mike"));
familylist.Add(new Fnamelist("john"));
familylist.Add(new Fnamelist("melon"));
familylist.Add(new Fnamelist("bab"));
listView1.ItemsSource = familylist;
listView1.Items.Refresh();
}
xaml :
<Button Content="show" Height="23" HorizontalAlignment="Left" Margin="331,79,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<ListView Height="129" HorizontalAlignment="Left" Margin="20,23,0,0" Name="listView1" VerticalAlignment="Top" Width="291">
<ListView.View>
<GridView>
<GridViewColumn Header="FirstName" DisplayMemberBinding="{Binding Path=Fname}"/>
</GridView>
</ListView.View>
</ListView>
when I clicked show button , it gives error :
Unable to cast object of type 'System.Windows.Controls.SelectedItemCollection' to type 'Fnamelist'.
whats the problem ?
Upvotes: 1
Views: 131
Reputation: 6547
The code in your button1_Click
event handler is trying to display the Fname
of a single item, where as listView1.SelectedItems
is a collection of items.
You can show the first selected item:
MessageBox.Show(((Fnamelist)listView1.SelectedItems[0]).Fname);
or iterate the selected items collection and do whatever you want inside, for example, MessageBox
:
foreach (var item in listview1.SelectedItems)
{
string fname = ((Fnamelist)item).Fname;
MessageBox.Show(fname);
}
On a side-note, you can remove the ToString()
call. It is redundent since Fname
is already a string.
Upvotes: 5