Reputation: 7517
how do i retrieve data from a table within a loop or something. That means I want to retrieve row by row at a time. but the sequence of rows may differ. For example, 1st time i want 5rd row,then 2nd, then 9...so on.
I searched it through the internet. I got only two answers.
Use several SqlConnection objects.
reader= sqlCommand.ExecuteReader(); While(reader.Read()){ reader["Column Name"].ToString(); }
If you got my problem, please help me Thank you.
Upvotes: 1
Views: 607
Reputation: 2011
Sounds like you should correct your data layer to return the values in the order you are going to process them. It would be easiest and fastest! :)
As an alternative I'd suggest that you load your result into a DataTable:
DataTable table = new DataTable();
using ( SqlCommand command = new SqlCommand() )
{
// TODO: Set up your command here
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
adapter.Fill(table);
}
}
// Use your DataTable like this...
if ( table.Rows.Count >= 5 ) {
DataRow firstRow = table.Rows[0]; // #1 row
DataRow fifthRow = table.Rows[4]; // #5 row
DataRow secondRow = table.Rows[1]; // #2 row
}
/Alex
Upvotes: 2
Reputation: 434
What exactly are you trying to achieve? Retrieve random rows from a DS or do you have certain criteria for selecting which rows you want returned? And if so couldn't you order them before loading them into the reader?
Upvotes: 0
Reputation: 42440
It's probably best to read your data into a DataSet, as shown in this example:
http://quickstart.developerfusion.co.uk/quickstart/howto/doc/adoplus/GetDataFromDB.aspx
Upvotes: 1
Reputation: 39274
Two ways, that I see:
1) Get all rows in one sql statement, then access the row you need in memory.
Or (of "everything" is too much or you need recent data)
2) Get only the specific row you need, and again for the next row.
Upvotes: 0
Reputation: 60190
The reader approach is usually the way to go, but your query (or SP) must already select the data in the order you want to retrieve it.
Alternatively you can load everything into a DataSet and do random access on the rows in it.
Upvotes: 0