I am getting an error here in sorting the gridview. My datasource is a var results, which I am getting thru a Linq query
protected void Page_Load(object sender, EventArgs e)
{
dt1 = obj1.Table1data().Tables[0];
dt2 = obj1.Table2data().Tables[0];
dt3 = obj1.Table3data().Tables[0];
var results = (
from table1 in dt1.AsEnumerable()
join table2 in dt2.AsEnumerable() on (int)table1["id"] equals (int)table2["id"]
join table3 in dt3.AsEnumerable() on (int)table1["id"] equals (int)table3["id"]
select new
{
id = (int)table1["id"],
S1= (int)table1["S1"],
P1= (double)table1["P1"],
P2= (int)table2["P2"],
P3= (double)table2["P3"],
P4 = (int)table3["P4"],
P5= (double)table3["P5"],
}).ToList();
Session["ds"] = results;
GridView1.DataSource = results;
GridView1.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataSet dataSet = (DataSet)Session["ds"];
DataTable dataTable = dataSet.Tables[0];
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
// here in the GridView1_sorting at DataSet dataSet = (DataSet)Session["ds"], I am getting an error
error:
Unable to cast object of type System.Collections.Generic.List`1[<>f__AnonymousType5`8[System.Int32,System.String,System.Int32,System.Double,System.Int32,System.Double,System.Int32,System.Double]]' to type 'System.Data.DataSet'
2) Also another question, What is the datatype of the var results.
Thanks
Sun
Session["ds"]holdsvar results, andresultsis aList<'A>, where'Ais an anonymous type generated by the compiler. You cannot cast this to aDataSet. If you want to put this into session and retrieve it later, declare a proper class, and then you can easily put the list into and out of Session.What I mean is that your query is building an an anonymous type because of the
selectstatementThis is normally fine, but you’re trying to use this result beyond the immediate local scope by putting it into session. You need to build a proper class to hold that data. Give it the right properties.
And then make your query
And when you invoke
ToList()and the result, you will haveList<MyData>. So when you go to retrieve this from session, this is what you would cast it to.