Reputation: 2442
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
Upvotes: 3
Views: 14313
Reputation: 126834
Session["ds"]
holds var results
, and results
is a List<'A>
, where 'A
is an anonymous type generated by the compiler. You cannot cast this to a DataSet
. 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 select
statement
select new
{
This 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.
public class MyData
{
// give it the appropriate properties you need
public int ID { get; set; }
public int S1 { get; set; }
public double P1 { get; set; }
public int P2 { get; set; }
public double P3 { get; set; }
public int P4 { get; set; }
public double P5 { get; set; }
// by the way... you should really come up with better names
// for these properties!
}
And then make your query
select new MyData
{
And when you invoke ToList()
and the result, you will have List<MyData>
. So when you go to retrieve this from session, this is what you would cast it to.
var list = (List<MyData>)Session["ds"];
Upvotes: 4