Select Rows range in DataTable in C# 2.0

theartha
theartha used Ask the Experts™
on
HI There,

How to select datatable by row range? i.e if I need to pull out records in datatable from row #1 - #10

DataRow[] foundRows = eventsDataTable.Select(queryDataSet2);

Any advice.

Thanks.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
try

var foundRows = EventsDatatable.AsEnumerable().Take(10).ToList();

Also, check this link

http://social.msdn.microsoft.com/Forums/ar/csharpgeneral/thread/9d403a63-3605-4032-97c0-7ee2368bcffe

If you want different ranges

use skip and take, check this other link:

http://stackoverflow.com/questions/3836431/datatable-select-by-row-range-c-sharp

Author

Commented:
@ralmada

I am a newbie using DataTable.

1. Connected to my database
2. Pulled the data from a table.
3. Created a DataTable
4. Using SQL Adapter, I fill the newly created dataTable.
5. Connection Closed.

------------

Now,

I have my DataTable with all the data.

-----------------------
Here is my code.


int minRows = 1;
int maxRows = 7;

string query = @" SELECT name,date, ROW_NUMBER() OVER (ORDER BY StartDateTime asc) AS RowNumber  from Emp  ";

Connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
DataTable eventsDataTable = new DataTable();
adapter.Fill(eventsDataTable);
Connection.Close();



            string queryDataTable3 = "StartDateTime >= #" + DateTime.Now.Date.ToString("d") + "#";
           
            DataRow[] foundRows;

            DataTable newEvents = new DataTable();
            newEvents.Columns.Add("StartDateTime");
            newEvents.Columns.Add("EndDateTime");
            newEvents.Columns.Add("RowNumber");

            foundRows = eventsDataTable.Select(queryDataTable3);

Now foundRows has 27 rows and I need to add a range of rows to another datatable. Say 1 to 7

Please advice.

Thanks.
Commented:
Thanks for your help ralmada, I fixed it.

 foreach (DataRow row in foundRows)
            {
                newEvents1.ImportRow(row);
                newEvents1.AcceptChanges();
            }

            DataTable newEvents2 = new DataTable();
            newEvents2 = newEvents1.Clone();

            DataRow newRows;

            for (int i = 0; i < maxRows; i++)
            {
               
                newRows = newEvents2.NewRow();              
                newEvents2.ImportRow(newEvents1.Rows);//

            }

Author

Commented:
I fixed it myself

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial