Reputation: 61
I have this problem with listview item and hoping that you guys can help me fix this. My goal is to fill listview with list and when user touches one these items, i want to have another view loaded. Adding items works fine, but when i get the value from selected item and typecast it to the correct object, it comes with " ‘invalid cast’ cannot cast..." and crashes.
FYI, I use the Android 4.0 sim, and these are part of the code:
SetContentView(Resource.Layout.ArchiveList);
ListView lstArchiveList = FindViewById<ListView>(Resource.Id.lstArchive);
if (lstArchiveList != null) {
ArrayAdapter<MobileContracts.Archive> archivesAdapter = new
ArrayAdapter<MobileContracts.Archive>(this, Resource.Layout.ListItem, sessionData.Archives.Archive);
lstArchiveList.Adapter = archivesAdapter;
lstArchiveList.TextFilterEnabled = true;
lstArchiveList.ItemClick += new EventHandler<AdapterView.ItemClickEventArgs>(lstArchiveList_ItemClick);
archivesAdapter.NotifyDataSetChanged();
}
OnClick event handler:
void lstArchiveList_ItemClick(object sender, AdapterView.ItemClickEventArgs e) {
SetContentView(Resource.Layout.SearchDocuments);
ListView lstEditableIndexList = FindViewById<ListView>(Resource.Id.lstEditableIndexList);
if (lstEditableIndexList != null) {
Console.WriteLine("sender type: {0}", sender.GetType().FullName);
Object currentItem = e.Parent.GetItemAtPosition(e.Position);
MobileContracts.Archive selectedArchive = (MobileContracts.Archive) currentItem; //invalid cast?
Toast.MakeText(Application, selectedArchive.Name + " => " + selectedArchive.Id, ToastLength.Short).Show();
}
Any help appreciated. Thank's a lot in advance.
Cheers, Inoel
Upvotes: 1
Views: 532
Reputation: 61
Never mind, I figure this out.
Replace this:
MobileContracts.Archive selectedArchive = (MobileContracts.Archive) currentItem; //invalid cast?
with this:
System.Reflection.PropertyInfo propertyInfo = currentItem.GetType().GetProperty("Instance");
MobileContracts.Archive selectedArchive = propertyInfo.GetValue(currentItem, null) as MobileContracts.Archive;
Upvotes: 1