c# – How to iterate through a DataTable

The Question :

150 people think this question is useful

I need to iterate through a DataTable. I have an column there named ImagePath.

When I am using DataReader I do it this way:

SqlDataReader dr = null;
dr = cmd.ExecuteReader();
while (dr.Read())
    TextBox1.Text = dr["ImagePath"].ToString();

How can I achieve the same thing using DataTable?

The Question Comments :
  • dr.Read() reads row by row from the network buffer, not row by row from the database.There is only one fetch from the database. Hence reading from a datatable is not going offer any performance gain.

The Answer 1

299 people think this answer is useful
DataTable dt = new DataTable();

SqlDataAdapter adapter = new SqlDataAdapter(cmd);


foreach(DataRow row in dt.Rows)
    TextBox1.Text = row["ImagePath"].ToString();

…assumes the connection is open and the command is set up properly. I also didn’t check the syntax, but it should give you the idea.

The Answer 2

33 people think this answer is useful
foreach (DataRow row in myDataTable.Rows)

I am writing this from memory.
Hope this gives you enough hint to understand the object model.

DataTable -> DataRowCollection -> DataRow (which one can use & look for column contents for that row, either using columnName or ordinal).

-> = contains.

The Answer 3

22 people think this answer is useful

You can also use linq extensions for DataSets:

var imagePaths = dt.AsEnumerble().Select(r => r.Field<string>("ImagePath");
foreach(string imgPath in imagePaths)
    TextBox1.Text = imgPath;

The Answer 4

5 people think this answer is useful

The above examples are quite helpful. But, if we want to check if a particular row is having a particular value or not. If yes then delete and break and in case of no value found straight throw error. Below code works:

foreach (DataRow row in dtData.Rows)
            if (row["Column_name"].ToString() == txtBox.Text)
                // Getting the sequence number from the textbox.
                string strName1 = txtRowDeletion.Text;

                // Creating the SqlCommand object to access the stored procedure
                // used to get the data for the grid.
                string strDeleteData = "Sp_name";
                SqlCommand cmdDeleteData = new SqlCommand(strDeleteData, conn);
                cmdDeleteData.CommandType = System.Data.CommandType.StoredProcedure;

                // Running the query.


                dtData = (DataTable)Session["GetData"];

                lblMsgForDeletion.Text = "The row successfully deleted !!" + txtRowDeletion.Text;
                txtRowDeletion.Text = "";
                lblMsgForDeletion.Text = "The row is not present ";


Add a Comment