tags:

views:

30

answers:

2

It's easy to bind a data source to something like a gridview or repeater, but how would I do it with a label? Heres the sql connection that I want to modify. By the way, I don't need 2 way binding.

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

The query I'm using:

SELECT Description FROM RbSpecials WHERE Active=1

+2  A: 
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;
    }
}

This will also ensure that in case of exception all disposable objects are disposed and will properly return the SQLConnection to the connection pool in order to be reused.

And finally assign the Text property of the label:

lblTest.Text = SqlConnection("SELECT Description FROM RbSpecials WHERE Active=1");
Darin Dimitrov
Thanks! It works great.
nick
A: 

use ExecuteReader rather than 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); 
               }
           }
        }

     }
}
Azhar