Question

when I try to cast a list item as an object, I get the following. "Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'ASPGigManager2.GigOpportunity'"

Is there anyway you can do this? Here is my code:

GigOpportunity gigOpportunity;
gigList.removeGig((GigOpportunity)lstGigs.SelectedItem);

I have tried to go the long way round and convert it to string but I still get a conversion error, string to GigOpportunity.

GigOpportunity gigOpportunity;
string test;
test = Convert.ToString(lstGigs.SelectedItem);
gigOpportunity = test;
Was it helpful?

Solution

Its as it says, you cannot convert a ListItem to GigOpportunity. And since this is ASP.NET, your original object no longer exists inside the list control. So, during your initial binding, set the DataValueField property to a unique value that identifies each gig (such as a primary key).

Then, on a callback, you have to find your original gig again. For example:

var selectedValue = lstGigs.SelectedValue;

var gig = gigList.Where(x => x.SomeKeyValue == selectedValue).Single();

gigList.Remove(gig);

Better yet, turn you gigList into a dictionary who's key is the same key you used as the value. Then, all you have to do is

gigDict.Remove(lstGigs.SelectedValue);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top