11

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();
}

Table

I need Something like below without loop when we have only one row,

String cn=row["ColumnName"].ToString()
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
TestQTP
  • 131
  • 1
  • 1
  • 8
  • What is a row value? Rows consist of columns so you should say what column you want – Gilad Green Aug 19 '16 at 13:04
  • 1
    Possible duplicate of [DataRow: Select cell value by a given column name](http://stackoverflow.com/questions/7119993/datarow-select-cell-value-by-a-given-column-name) – sr28 Aug 19 '16 at 13:05

5 Answers5

20

This is the way:

string Text = dataTable.Rows[0]["ColumnName"].ToString();
Paul Pérez
  • 320
  • 3
  • 9
3

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();
1

Convert.ToString(row["ColumnName"]);

Aniruddh
  • 11
  • 1
0

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.

David
  • 208,112
  • 36
  • 198
  • 279
0
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"));

            }
        }
Oscar Larsson
  • 83
  • 1
  • 10