Wednesday, December 7, 2011

SqlDataAdapter To Retrieve Multiple Rows


SqlDataAdapter To Retrieve Multiple Rows

The following code illustrates how to use a SqlDataAdapter object to issue a command that generates a DataSet or DataTable. It retrieves a set of product categories from the SQL Server Northwind database.

using System.Data;

using System.Data.SqlClient;



public DataTable RetrieveRowsWithDataTable()

{

  using ( SqlConnection conn = new SqlConnection(connectionString) )

  {

    conn.Open();

    SqlCommand cmd = new SqlCommand("DATRetrieveProducts", conn);

    cmd.CommandType = CommandType.StoredProcedure;

    SqlDataAdapter adapter = new SqlDataAdapter( cmd );

    DataTable dataTable = new DataTable("Products");

    adapter .Fill(dataTable);

    return dataTable;

  }

}

 


To use a SqlAdapter to generate a DataSet or DataTable

1. Create a SqlCommand object to invoke the stored procedure and associate this with a SqlConnection object (shown) or connection string (not shown).
2. Create a new SqlDataAdapter object and associate it with the SqlCommand object.
3. Create a DataTable (or optionally, a DataSet) object. Use a constructor argument to name the DataTable.
4. Call the Fill method of the SqlDataAdapter object to populate either the DataSet or DataTable with the retrieved rows.