I have a session object, which contains a list of objects..
Session.Add("errorlist",errorlist);
Now i want to loop through this errorlist in another function. I tried, but it gives following error:
foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'
This is what I tried:
var error = Session["errorlist"];
foreach (var item in error)
{
//Something here
}
I can see a list of objects in "error" variable.
Everything that goes into session is of type System.Object by default. So your var statement will not have the correct type.
You need to cast it when pulling back out of session.
var error = (List<MyObject>)Session["errorlist"];
A better way would be to use a safe cast and check for null:
var error = Session["errorlist"] as List<MyObject>;
if(error != null){
//Do stuff here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With