2009-11-21 220 views
86

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

当我使用DataReader我做这种方式:

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

我如何能实现使用DataTable是一回事吗?

+1

dr.Read()由网络缓冲区读取一行行,不按行从database.There行只有一个从数据库中获取。因此从数据表中读取不会提供任何性能增益。 – developer747 2013-07-05 22:08:48

回答

192
DataTable dt = new DataTable(); 

SqlDataAdapter adapter = new SqlDataAdapter(cmd); 

adapter.Fill(dt); 

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

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

+4

+1。你击败了我几秒钟:) – shahkalpesh 2009-11-21 04:28:12

+0

假设有人正在寻找'linq'解决方案,并想知道上述解决方案中的'(cmd)'在哪里? – Jogi 2016-05-07 14:39:17

+0

@RehanKhan - 'cmd'是要执行的SQL命令。如果你使用LINQ,你可以编写你的LINQ查询并以这种方式得到你的结果。 – 2016-05-07 20:03:41

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

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

DataTable - >DataRowCollection - >DataRow(其中之一可以使用&外表列内容该行,或者使用COLUMNNAME或有序)。

- > =包含。

14

您还可以使用LINQ扩展数据集:

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

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

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 "; 
      } 
     } 
+0

这是一个疯狂的方式来完成删除行!只发出一个TSQL删除语句! – 2017-02-10 00:15:25