Click here to Skip to main content
15,176,948 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
sir
I have two datatables I am joining these two tables using linq query
I have following code.
C++
DataTable dt = new DataTable();
           dt.Columns.Add("ID",typeof(string));
           dt.Columns.Add("Name", typeof(string));

           DataRow dr = dt.NewRow();
           dr["ID"] = "1";
           dr["Name"] = "Test1";
           dt.Rows.Add(dr);

           dr = dt.NewRow();
           dr["ID"] = "2";
           dr["Name"] = "Test2";
           dt.Rows.Add(dr);

           DataTable dt1 = new DataTable();
           dt1.Columns.Add("ID", typeof(string));
           dt1.Columns.Add("Product", typeof(string));

           dr = dt1.NewRow();
           dr["ID"] = "1";
           dr["Product"] = "Test-Product";
           dt1.Rows.Add(dr);
           dataGridView1.DataSource = dt;
           dataGridView2.DataSource = dt1;



           var c = from p in dt.AsEnumerable()
                   join d in dt1.AsEnumerable() on p.Field<string>           ("ID")        equals d.Field<string>("ID")
                          select new { ID = p.Field<string>("ID"), Name = p.Field<string>("Name"), Product = d.Field<string>("Product")};


I want to display the above Linq query c display into gridview
I have a code
C++
dataGridView3.DataSource = c.CopyToDataTable<DataRow>();

But it is error
Pls give me answer.
Posted

Just set the data source to c
as in dataGridView3.DataSource = c;
   
v2
Comments
yesotaso 28-May-11 20:38pm
   
Ref MSDN:
All LINQ query operations consist of three distinct actions:
1- Obtain the data source.
2- Create the query.
3- Execute the query.

So, in this context 3rd step is missing.
OK, then what?
Again MSDN: The query variable itself only stores the query commands. The actual execution of the query is deferred until you iterate over the query variable in a foreach statement. This concept is referred to as deferred execution.Queries that perform aggregation functions over a range of source elements must first iterate over those elements. Examples of such queries are Count, Max, Average, and First. These execute without an explicit foreach statement because the query itself must use foreach in order to return a result. To force immediate execution of any query and cache its results, you can call the ToList<tsource> or ToArray<tsource> methods.
TL;DR... you should have read it :P Correct answer is given by Wonde
Dan Mos 29-May-11 4:58am
   
you are correct.
I usually call TiList or toArray directly on the query hence the mistake.
Just convert you result to ToList.i.e
dataGridView3.DataSource = c.ToList();


That's it!
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900