How to iterate through a DataTable

后端 未结 4 1423
死守一世寂寞
死守一世寂寞 2020-11-29 19:51

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

When I am using DataReader I do it this way:

相关标签:
4条回答
  • 2020-11-29 20:24

    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;
    }
    
    0 讨论(0)
  • 2020-11-29 20:25
    foreach (DataRow row in myDataTable.Rows)
    {
       Console.WriteLine(row["ImagePath"]);
    }
    

    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.

    0 讨论(0)
  • 2020-11-29 20:33

    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.
                    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 讨论(0)
  • 2020-11-29 20:45
    DataTable dt = new DataTable();
    
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    
    adapter.Fill(dt);
    
    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.

    0 讨论(0)
提交回复
热议问题