Search code examples
c#sql-server-2008-express

SQL data retrieve - C#


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.

  1. Use several SqlConnection objects.

  2. reader= sqlCommand.ExecuteReader(); While(reader.Read()){ reader["Column Name"].ToString(); }

If you got my problem, please help me Thank you.


Solution

  • 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