Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
hi,
i have a dataset which has 4 datatables in it and some records in each datatable.i need to select oly the top one record from these 4 tables and save it in either a datatable or any dataset and display these 4 records in my grid. pls help me how to do it in asp.net using c#.pls help me
Posted

try the following code.

C#
DataTable dt1_new = new DataTable();
dt1_new.Rows.Add(dt1.AsEnumerable().FirstOrDefault());
dt1_new.Rows.Add(dt2.AsEnumerable().FirstOrDefault());
dt1_new.Rows.Add(dt3.AsEnumerable().FirstOrDefault());
dt1_new.Rows.Add(dt4.AsEnumerable().FirstOrDefault());
 
Share this answer
 
Getting the first record from a DataTable is not a hard thing to do. Simply access row 0 only. That would look something like this:
C#
var row = DataSet.DataTables[0].Rows[0];

That will give you a DataRow that contains the first record from the first table in the DataSet. You could do this for each of your four tables. Then you could create a new DataTable and insert these four rows into it. The key here though would be that the four rows would have to have matching column names and types. Here is how you would manually create a DataTable:
http://www.dotnetperls.com/datatable[^]

The bigger question I see here though is why are you do it this way? It seems like you could at least limit your query to only give you the first row in each table (SELECT TOP 1 * FROM table). You might also be able to do the joining of the four entries at the database level as well. Something like this:
SQL
SELECT TOP 1 FieldA, FieldB FROM table1
UNION ALL
SELECT TOP 1 FieldA, FieldB FROM table2
UNION ALL
SELECT TOP 1 FieldA, FieldB FROM table3
UNION ALL
SELECT TOP 1 FieldA, FieldB FROM table4

That would give you the top record from each table and join them together. The output would be four rows.

Obviously these last suggestions would be dependent on how your environment is set up, but if possible I would definitely recommend going this way.
 
Share this answer
 

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