ASP.Net C# Convert DataSet to DataTable

Updated on 21 Aug 2012,
Published on 08 Sep 2008

In ASP.Net, you can convert DataSet to DataTable using single C# code line. But you must have some knowledge about DataSet. As the name suggests DataSet consists of collection of DataTable that can store the table schema i.e. column names and their datatype. DataTable collection of DataSet stores each table at zero-based index that can be retrieved as a DataTable by passing the index of table whose data you want to display on the ASP.Net web page. For converting the ASP.Net DataSet to DataTable you can select the DataTable based on its index in the DataTable Collection and initialize the DataTable class object with it. This will copy the DataTable schema as well as its data into the DataTable object. 

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();


// 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() + "<br/>");

Continue to next tutorial: ASP.Net C# Convert DataSet to DataView to learn how to transform record set in dataset to datatable.

4 Responses to "ASP.Net C# Convert DataSet to DataTable"
I am developing a project in with C# i want to convert dataset to datalist.How i do this?
Pooja NK
Hey thanks, This is what I was looking for. Handy and quick!!
hi very good help!!
Thanks a lot. Useful for me at very crucial time.
Leave a Comment
* required
* required
* will not be published
* optional
* hint:
  • Subscribe via Email