Monday, January 30, 2012

How to iterate through a DataTable in C#?

It often happens when you have a datatable in c# but you don't know how many columns has and its names. So, please take a look at this simple example to loop over a datatable rows. If you have any question don't hesitate in comments section.
DataTable dtCompanies = GetCompanies();
        string Message = "";
        int rowCount = 0;
        foreach (DataRow dRow in dtCompanies.Rows)
        {
            Message += "Row:" + rowCount + ", Columns: ";

            foreach (DataColumn dCol in dtCompanies.Columns)
            {
                Message += dCol.ColumnName + "( " + dtCompanies.Rows[rowCount][dCol].ToString() + " ) ";
            }
            rowCount++;
        }

2 comments:

  1. how to get data fro dataset and display it on server table control dynamically when don't know the structure of table i.e. don't have information about how many columns .

    ReplyDelete
  2. accessing Columns properties should do it. Otherwise - could you describe better the requirement?

    ReplyDelete