extract values from DataTable with single row

user4221591 picture user4221591 · Mar 14, 2015 · Viewed 71.4k times · Source

How to extract the values from data table having single row and assign to asp labels.

private void GetUser(string userId)
{
    dbr.SelectString = "select name, gender,  address, contactno from userInfo where id = = '" + userId + "' --"; // return single row
    DataTable dt = dbr.GetTable();
    //DataRow row = dt.Rows[0];
    // how to retrieve the fields from the data table.
    //lbl_name = name.ToString();
    //lbl_gender = gender.ToString();
    //lbl_contact = contactno.ToString();
}

I thought of using foreach loop but the datatable contains only single row. How can I pass empty string in the case of NULL cells. Also, can I extract the values from datatable via list?

Answer

ASh picture ASh · Mar 14, 2015
private void GetUser(string userId)
{
    dbr.SelectString = "select name, gender,  address, contactno from userInfo where id = = '" + userId + "' --"; // return single row
    DataTable dt = dbr.GetTable();
    if (dt.Rows.Count > 0) 
    {
        DataRow row = dt.Rows[0];

        lbl_name = row["name"].ToString();
        lbl_gender = row["gender"].ToString();
        lbl_contact = row["contactno"].ToString();
    }
}