如何迭代一个DataTable

我需要遍历一个DataTable 。 我有一个名为ImagePath的列。

当我使用DataReader我这样做:

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

如何使用DataTable来实现同样的function?

 DataTable dt = new DataTable(); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(dt); foreach(DataRow row in dt.Rows) { TextBox1.Text = row["ImagePath"].ToString(); } 

…假定连接已打开,命令设置正确。 我也没有检查语法,但它应该给你的想法。

 foreach (DataRow row in myDataTable.Rows) { Console.WriteLine(row["ImagePath"]); } 

我从记忆中写这个。
希望这给你足够的提示来理解对象模型。

DataTable – > DataRowCollection – > DataRow (可以使用&查找该行的列内容,使用columnName或ordinal)。

– > =包含。

你也可以使用DataSet的linq扩展:

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

上面的例子是相当有帮助的。 但是,如果我们想检查一个特定的行是否有特定的值。 如果是,那么删除并中断,如果没有值发现直投错误。 下面的代码工作:

 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. conn.Open(); cmdDeleteData.ExecuteNonQuery(); conn.Close(); GetData(); dtData = (DataTable)Session["GetData"]; BindGrid(dtData); lblMsgForDeletion.Text = "The row successfully deleted !!" + txtRowDeletion.Text; txtRowDeletion.Text = ""; break; } else { lblMsgForDeletion.Text = "The row is not present "; } }