如何将数据源绑定到标签控件

时间:2010-09-05 08:06:57

标签: c# asp.net .net

将数据源绑定到gridview或repeater之类的东西很容易,但是如何使用标签呢?继承人我要修改的SQL连接。顺便说一句,我不需要2路绑定。

public void Sql_Connection(string queryString)
{
    SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString);
    SqlCommand cmd = new SqlCommand(queryString, conn);
    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
}

我正在使用的查询:

SELECT描述FROM RbSpecials WHERE Active = 1

3 个答案:

答案 0 :(得分:3)

public string SqlConnection(string queryString)
{
    using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString))
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = queryString;
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                // This will return the first result 
                // but there might be other
                return reader.GetString(0);
            }
        }
        return null;
    }
}

这也将确保在异常情况下处理所有一次性对象并将SQLConnection正确地返回到连接池以便重复使用。

最后分配标签的Text属性:

lblTest.Text = SqlConnection("SELECT Description FROM RbSpecials WHERE Active=1");

答案 1 :(得分:1)

使用ExecuteReader而不是ExecuteNonQuery

public void Sql_Connection(string queryString)
{
     using(SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings"RBConnectionString"].ConnectionString))
     {
        using(SqlCommand cmd = new SqlCommand(queryString, conn))
        {
           conn.Open();
           using(SqlDataReader rdr = cmd.ExecuteReader())
           {
               while(rdr.Read())
               {
                   lblDescription.Text = rdr.GetString(0); 
               }
           }
        }

     }
}

答案 2 :(得分:0)

using (SqlConnection con = new SqlConnection(Connection_String))
{
   SqlCommand cmd = new SqlCommand("select * from Customers", con);
   cmd.CommandType = CommandType.StoredProcedure;
   SqlDataReader adpt = cmd.ExecureReader();
   if(rdr.Read())
    {
      lblName.Text = rdr[0].ToString();
    }
 }