TestQTP
TestQTP

Reputation: 141

How to get row value by just giving column name in DataTable

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

Upvotes: 12

Views: 62504

Answers (5)

Oscar Larsson
Oscar Larsson

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

Brijesh Kumar Tripathi
Brijesh Kumar Tripathi

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

Paul P&#233;rez
Paul P&#233;rez

Reputation: 350

This is the way:

string Text = dataTable.Rows[0]["ColumnName"].ToString();

Upvotes: 23

Aniruddh
Aniruddh

Reputation: 11

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

Upvotes: 1

David
David

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

Related Questions