Looping through all rows of the DataTable

Posted by in C# category on for Beginner level | Views : 96033 red flag
Rating: 5 out of 5  
 2 vote(s)

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

using System.Data;


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[0];
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.
Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com

Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Akiii on: 4/7/2011 | Points: 25
crystal clear explanation....
thank you sir....


Login to post response

Comment using Facebook(Author doesn't get notification)