12

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()
2
  • What is a row value? Rows consist of columns so you should say what column you want Commented Aug 19, 2016 at 13:04
  • 1
    Possible duplicate of DataRow: Select cell value by a given column name Commented Aug 19, 2016 at 13:05

5 Answers 5

23

This is the way:

string Text = dataTable.Rows[0]["ColumnName"].ToString();
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

Comments

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.

2 Comments

Note that there is no row.Item in DataRow
it not row.Item ... it's row.ItemArray
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"));

            }
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.