[Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1057
  • Last Modified:

asp.net c# 2.0 bind to label?

How do I query SQL Server for a value, bind to a label and close all connections that need to closed?

protected void Page_Load(object sender, EventArgs e)
String OL = Request.QueryString["OL"];

SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IntrConnection"].ConnectionString);
string strSQL = "select email_id from table where officeLoc = '" + OL + "' and title = 'RCA'";
SqlDataAdapter myCommand = new SqlDataAdapter(strSQL, myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds, "FP");
Source = new DataView(ds.Tables["FP"]);

//bind to label
LabelRCA.Text = DataSet1.Tables(0).Rows(0).Item("email_id").ToString();

//close connections


Or is there a way to bind to a variable?
  • 2
1 Solution
Pretty sure you cant bind to a label in the way you want to.....like you can in a winforms app.

for your connection you may want to use the using contruct, this will close and dispose the connection implicitly.  You may also want to consider using a datareader which is alot faster...and if you only want the one value back then you want to use ExecuteScalar on you sqlcommand object.

using(SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["IntrConnection"].ConnectionString)) {
// use connection in here with reader or adapter

hope this helps

fwstealAuthor Commented:
I get the using; but how would I bind to a label or a literal?
like i said i dont think you can bind directly to a label that isnt within a template field on a gridview etc.

using execute scalar would be done....

using(sqlconnection....) {
  using(sqlcommand cmd = new sqlcommand("select name from table where id=1", conn)){
    Label1.Text = cmd.ExecuteScalar.ToString();

or if you have the value in a datatable already you should get from there.


Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now