Menu

Linq to DataTable

First Declare  DataClassesDataContext object.


DataClassesDataContext db = new DataClassesDataContext();

      DataTable dt = new DataTable();
/*Linq Query to Datatable*/
var query = from s in db.Users
select s;
        //Here call function.
dt = ToDataTable(db, query);
grdlist.DataBind();

Here code to convert Linq query to DataTable.


public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
{
if (query == null)
{
throw new ArgumentNullException("query");
}
IDbCommand cmd = ctx.GetCommand(query as IQueryable);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = (SqlCommand)cmd;
DataTable dt = new DataTable("sd");
try
{
cmd.Connection.Open();
adapter.FillSchema(dt, SchemaType.Source);
adapter.Fill(dt);
}
finally
{
cmd.Connection.Close();
}
return dt;
}

No comments

Leave a Reply


− 9 = 0

Categories