Thursday, September 11, 2008

C# Code for ASP.Net Convert DataSet to DataTable

C# Code for ASP.Net Convert DataSet to DataTable

// SQL Select Command
SqlCommand mySqlSelect = new SqlCommand("select * from categories", mySQLconnection);
mySqlSelect.CommandType = CommandType.Text;

SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlSelect);

DataSet myDataSet = new DataSet();

mySqlAdapter.Fill(myDataSet);


// Convert DataSet to DataTable by getting DataTable at first zero-based index of DataTableCollection
DataTable myDataTable = myDataSet.Tables[0];


Above C# code shows how to fill the DataSet with data retrieved from the SQL Database and convert it into a single DataTable. Next step is to display the data stored in DataTable. You can bind the DataTable directly to the ASP.Net Data presentation controls such as GridView, DataList or repeater to display the data. Or you can read the data stored in each DataRow using the C# foreach loop as following:

// foreach loop to get each DataRow of DataTable retrieved from DataSet
foreach (DataRow dRow in myDataTable.Rows)
{ Response.Write(dRow[ "categoryId" ].ToString() + " " + dRow[ "categoryName" ].ToString() + "
");

}