Just use an index to access each element. The following code would acccess the first element in the list. the name of the property you are trying to access. each datarow will maintain the schema of the datatable that it came from so you still have columns in the datarow.
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.
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.
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;
}
There are already nice solution has been given. The below code can help others to query over datatable and get the value of each row of the datatable for the ImagePath column.
for (int i = 0; i < dataTable.Rows.Count; i++)
{
var theUrl = dataTable.Rows[i]["ImagePath"].ToString();
}
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 ";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With