Looping through all rows of the DataTable
Posted by Sheo Narayan
on 10/8/2007 for Beginner level | Views : 63828
If you found plagiarised (copied)
or inappropriate content,
please let us know
the original source along with your correct email id (to communicate) for further action.
Rating: 5 out of 5
Here is the working example of looping through all rows of the DataTable. You can download the code and simply run it by placing to your IIS root folder.
Let me explain you looping through all rows of the DataTable step wise.
Download source code for Looping through all rows of the DataTable
Namespace to Use
First lets place an asp:Literal control on your page. This control will be used to write the rows values as a string. (You may use asp:Label control too but literal best suits when you need to write raw html from server side)
Now get the data into DataTable using any of the DataSource. In this example I have used one .xml file.
Finally, write ForEach loop and manipulate the rows in whatever way you want.
Following is the function that will loop through the DataTable and print the data as displayed into the picture above.
private void LoadDataTable()
string str = string.Empty;
string path = Server.MapPath("~/GridData.xml");
int i = 0;
DataSet dSet = new DataSet();
DataTable dTable = dSet.Tables;
foreach (DataRow dRow in dTable.Rows)
str += "ROW " + i.ToString() + " : <b>Name: </b>" + dRow["FirstName"].ToString() + " " + dRow["LastName"].ToString() + ", <b>Address: </b>"+ dRow["Address"].ToString() +", <b>Profession: </b>" + dRow["Profession"].ToString() + "<br />";
litText.Text = str;
In the above function, I am declaring one dataset and getting data from .xml file using ReadXml method. Storing that datatable into a local DataTable variable. Then writing ForEach loop to loop through all the rows of the DataTable and storing into the string variabbles and finally specifying the .text property of the asp:literal control.
The working example is attached with this article, don't forget to download if you are facing any problem.
Found interesting? Add this to: