Reputation: 41
I have a table from a database, i want display a value from table to my label1. This is my code:
string query="Data Source=Bun; user Id=sa; Password=sa; Initial Catalog=eBilling;";
SqlConnection con = new SqlConnection(query);
con.Open();
string query1 = "select prodName from ProductMaster where @name='Bar Counter' ";
SqlCommand cmd = new SqlCommand(query1, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
label1.Text = dr.GetValue(1).ToString();
textBox1.Text = dr.GetValue(0).ToString();
}
but after that, i must click on this label to display the value. What can i do with this code to display my value in label while don't need click to anything?
Upvotes: 0
Views: 8598
Reputation: 3661
If this is for the web application:
In order to show the label as soon as user opens the page. You must write the code in page load. Also If you want to display this Label only the first time and after that value changes over some event, then place the code as:
..Page_Load(..)
{
(!IsPostBack)
{
}
}
So that Label shows value first time page loads. Any doubt you can ask again. :)
For window application logic remains the same.
private void label1_Click_1(object sender, EventArgs e) {}
call on Page Load like:
Page_Load(...)
{
label1_Click_1(null, null);
}
Upvotes: 0
Reputation: 28528
Write a different function with your code and call it in page_load
events and other events if required:
protected void Page_Load(object sender, EventArgs e)
{
setLableText();
}
private void setLableText()
{
string query="Data Source=Bun; user Id=sa; Password=sa; Initial Catalog=eBilling;";
SqlConnection con = new SqlConnection(query);
con.Open();
string query1 = "select prodName from ProductMaster where @name='Bar Counter' ";
SqlCommand cmd = new SqlCommand(query1, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
label1.Text = dr.GetValue(1).ToString();
textBox1.Text = dr.GetValue(0).ToString();
}
}
Upvotes: 1
Reputation: 13474
As @wqrahd said
protected void Page_Load(object sender, EventArgs e)
{
string query="Data Source=Bun; user Id=sa; Password=sa; Initial Catalog=eBilling;";
SqlConnection con = new SqlConnection(query);
con.Open();
string query1 = "select prodName from ProductMaster where @name='Bar Counter' ";
SqlCommand cmd = new SqlCommand(query1, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) {
label1.Text = dr.GetValue(1).ToString();
textBox1.Text = dr.GetValue(0).ToString();
}
Upvotes: 1