only My site

Saturday, June 21, 2008

Add Dataset table using Reader

// connection and query details
String connect = "your-connection-string";
const String SQL = "SELECT TOP 5 OrderID, OrderDate, ShipName, ShipCity, "
+ "ShipCountry FROM [Orders];"
+ "SELECT TOP 5 * FROM [Order Details];"
+ "SELECT TOP 5 CustomerID, CompanyName, Address, City, "
+ "Country FROM [Customers]";

// create a connection, command and get a DataReader
using (SqlConnection con = new SqlConnection(connect))
{
SqlCommand cmd = new SqlCommand(SQL, con);
con.Open();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

// create an array of table names for first two incoming rowsets
String[] tablenames = new String[] {"Orders", "Order Details"};

// load the data from the DataReader
// no existing data, but have to provide a value for LoadOptions
// so use OverwriteRow - makes no difference in this case
DataSet ds = new DataSet();
ds.Load(reader, LoadOption.OverwriteRow, tablenames);

// load another table directly using the Load method
DataTable dt = new DataTable();
dt.TableName = "Customers";
dt.Load(reader);
ds.Tables.Add(dt);

// display the results
...
}

No comments: