将数据集或数据表中的记录绑定到标签



伙计们,我想将从数据库返回的两条记录打印到标签中。我使用数据集,浏览列,但不能绑定,因为标签没有数据源。下面是我的代码。

        SqlDataAdapter adp = new SqlDataAdapter();
        adp.SelectCommand = cmd;
        DataSet ds = new DataSet();
        adp.Fill(ds);

    if (ds.Tables[0].Rows.Count > 0)
    {
        lblClient.Enabled = true;
        lblClient.Text = Convert.ToString(ds.Tables[0].Columns[0]);
        lblBranch.Text = Convert.ToString(ds.Tables[0].Columns["Bname"]);

    }
    connection.Close();

当我尝试上述操作时。它只返回列名(即指定的字符串)。任何替代办法将不胜感激。

您不需要列的文本,而是DataRow值:

lblClient.Text = ds.Tables[0].Rows[0].Field<string>(0);
lblBranch.Text = ds.Tables[0].Rows[0].Field<string>(1);

或按列名(假定为第一个名称):

lblClient.Text = ds.Tables[0].Rows[0].Field<string>("Cname");
lblBranch.Text = ds.Tables[0].Rows[0].Field<string>("Bname");

仅当表至少包含一行时,此操作才有效。所以你必须检查一下。

您需要指示该行具有您想要的行。使用代码,您可以选择数据表的一列

SqlDataAdapter adp = new SqlDataAdapter();
        adp.SelectCommand = cmd;
        DataSet ds = new DataSet();
        adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
    lblClient.Enabled = true;
    lblClient.Text = Convert.ToString(ds.Tables[0].Rows[0].[0]);
    lblBranch.Text = Convert.ToString(ds.Tables[0].Rows[0].["Bname"]);

}
connection.Close();

最新更新