如何遍历DataTable

hap*_*ile 132 c# asp.net

我需要遍历一个DataTable.我有一个名为的专栏ImagePath.

当我使用时,DataReader我这样做:

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

我怎样才能使用相同的东西DataTable

Jus*_*ner 270

DataTable dt = new DataTable();

SqlDataAdapter adapter = new SqlDataAdapter(cmd);

adapter.Fill(dt);

foreach(DataRow row in dt.Rows)
{
    TextBox1.Text = row["ImagePath"].ToString();
}
Run Code Online (Sandbox Code Playgroud)

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


sha*_*esh 29

foreach (DataRow row in myDataTable.Rows)
{
   Console.WriteLine(row["ImagePath"]);
}
Run Code Online (Sandbox Code Playgroud)

我是从记忆中写的.
希望这能为您提供足够的提示来理解对象模型.

DataTable- > DataRowCollection- > DataRow(哪一个可以使用&查找该行的列内容,使用columnName或ordinal).

- > =包含.


Lee*_*Lee 20

您还可以对DataSet使用linq扩展:

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

  • 请注意,要为“DataTable”添加“AsEnumerable()”,您需要将“System.Data.DataSetExtensions”添加为依赖项。 (2认同)

小智 13

已经给出了很好的解决方案。下面的代码可以帮助其他人查询数据表并获取数据表每一行的 ImagePath 列的值。

  for (int i = 0; i < dataTable.Rows.Count; i++)
  {
       var theUrl = dataTable.Rows[i]["ImagePath"].ToString();
  }
Run Code Online (Sandbox Code Playgroud)


bay*_*max 5

上面的例子很有帮助。但是,如果我们想检查特定行是否具有特定值。如果是,则删除并中断,如果没有发现值,则直接抛出错误。下面的代码有效:

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 ";
            }
        }
Run Code Online (Sandbox Code Playgroud)