从DataTable中提取单行的值

时间:2015-03-14 07:50:52

标签: c# asp.net datatable datarow

如何从具有单行的数据表中提取值并分配给asp标签。

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

我想过使用foreach循环但是数据表只包含单行。 如何在NULL单元格的情况下传递空字符串。另外,我可以通过列表从数据表中提取值吗?

4 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分:0)

要获取所有行的列表,您需要一个类

  class Lbl()
            {
                public string Name {get; set;}
                public string Gender {get; set;}
                public string Contact {get; set;}
            }

填写课程:

 List<Lbl> list = new List<Lbl>();
            foreach(DataRow row in dt.Rows)
            {
                Lbl lbl = new Lbl();
                lbl.Name = row["name"].ToString();
                lbl.Gender = row["gender"].ToString();
                lbl.Contact = row["contactno"].ToString();

                list.add(lbl);
            }

答案 2 :(得分:0)

仅一行

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

答案 3 :(得分:0)

已经很晚了,但是我认为您正在寻找的是下面的代码,该数据表是查询的结果。然后将该DT及其所有行和列解析为字符串。

DataTable dt = Execute_Query(Connection, query);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    J = dt.Rows.Count;

                    StringBuilder sb = new StringBuilder();

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        for (int j = 0; j < dt.Columns.Count; j++) 
                        {
                            sb.Append(dt.Rows[i][j] + ",");
                        }
                        sb.Append("\n");
                    }

                    Logger.Info(sb.ToString());
                }
            }