c# - trouble about get value from selecteditems -
i want selecteditems
values in listview` not work!
i have no problem when selecting 1 item want work in extended mode shows of selected items.
my code :
list<fnamelist> familylist = new list<fnamelist>(); public class fnamelist { public fnamelist(string fname) { this.fname = fname; } private string fname = string.empty; public string fname { { 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 clicked show button , gives error :
unable cast object of type 'system.windows.controls.selecteditemcollection' type 'fnamelist'.
whats problem ?
the code in button1_click
event handler trying display fname
of single item, listview1.selecteditems
collection of items.
you can show first selected item:
messagebox.show(((fnamelist)listview1.selecteditems[0]).fname);
or iterate selected items collection , whatever want inside, example, messagebox
:
foreach (var item in listview1.selecteditems) { string fname = ((fnamelist)item).fname; messagebox.show(fname); }
on side-note, can remove tostring()
call. redundent since fname
string.
Comments
Post a Comment