Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract values from DataTable with single row

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?

like image 621
user4221591 Avatar asked Mar 14 '15 07:03

user4221591


2 Answers

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();
    }
}
like image 121
ASh Avatar answered Oct 05 '22 00:10

ASh


Simply in one line

dbr.SelectString = "select name, gender,  address, contactno from userInfo where id = = '" + userId + "' --"; 
DataTable DataTable_Values= dbr.GetTable(); 
lbl_name =  DataTable_Values.Rows[0].Field<string>("name");
lbl_gender =  DataTable_Values.Rows[0].Field<int>("gender");
lbl_contact =  DataTable_Values.Rows[0].Field<int>("contact")
like image 27
AhmadMM Avatar answered Oct 05 '22 02:10

AhmadMM