Reputation: 141
Is it possible to get a row value by giving column name when DataTable holds a single row, without iteration.
foreach(DataRow row in dt.Rows)
{
string strCity = row["City"].ToString();
}
I need Something like below without loop when we have only one row,
String cn=row["ColumnName"].ToString()
Upvotes: 12
Views: 62504
Reputation: 83
DataTable dt = new DataTable();
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
StringBuilder html = new StringBuilder();
foreach (DataRow row in dt.Rows)
{
html.Append(row.Field<Int32>("Columname"));
}
}
Upvotes: 0
Reputation: 2976
Use following code to get the value of the first row of the DataTable without iteration:
string strCity = string.Empty;
if (yourDataTable.Rows.Count > 0)
strCity = yourDataTable.Rows[0]["City"].ToString();
Upvotes: 3
Reputation: 350
This is the way:
string Text = dataTable.Rows[0]["ColumnName"].ToString();
Upvotes: 23
Reputation: 218847
This is attempting to index the row itself:
row["ColumnName"].ToString()
What you're looking for is to index the items within the row:
row.Item["ColumnName"].ToString()
when DataTable holds a single row, without iteration
If you're guaranteed that there is a row, you can reference it directly:
dt.Rows[0].Item["ColumnName"].ToString()
As with any indexing, you should probably do some bounds checking before trying to index it though.
Upvotes: 0