Get LINQ to SQL results into a DataTable in asp.net

Linq to sql is a microsofts powerful tool to develop critical application faster.In Linq to sql the query result is in Generic list of generic  ienumerable type.


 If you want result set in DataTable you need to convert this generic list result into datatable. To convert LINQ to SQL results into a DataTable use following Code


 DataClassesDataContext dc=new DataClassesDataContext();
        var results = dc.products.ToList();

        DataTable dt = new DataTable();
        List<product> lst = results;
        PropertyInfo[] props= typeof(product).GetProperties();
        foreach (var prop in props)
        {
            dt.Columns.Add(prop.Name);
        }
        foreach (var item in lst)
        {
            var rowa = new object[props.Length];

            for (int i = 0; i < props.Length; i++) 
            {
                rowa[i] = props[i].GetValue(item, null);
            
            }

            dt.Rows.Add(rowa);
        
        
        }

     
        GridView1.DataSource = dt;
       
        GridView1.DataBind();

Comments