[英]How to get value from database to a label?
我有一個來自數據庫的表,我想顯示一個從表到我的label1的值。 這是我的代碼:
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();
}
但是之后,我必須單擊該標簽以顯示該值。 我可以用此代碼做什么來在標簽中顯示我的值,而無需單擊任何內容?
將此代碼放在WinForm的page_load
方法中。
正如@wqrahd所說
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();
}
用您的代碼編寫一個不同的函數,並在page_load
事件和其他事件(如果需要)中調用它:
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();
}
}
如果這是針對Web應用程序的:
為了在用戶打開頁面后立即顯示標簽。 您必須在頁面加載中編寫代碼。 另外,如果您只想第一次顯示此Label,並且該值在某個事件中發生更改之后,則將代碼放置為:
..Page_Load(..)
{
(!IsPostBack)
{
}
}
這樣,Label會在首次加載頁面時顯示出價值。 如有任何疑問,您可以再次詢問。 :)
對於窗口應用程序,邏輯保持不變。
private void label1_Click_1(object sender, EventArgs e) {}
調用頁面加載,例如:
Page_Load(...)
{
label1_Click_1(null, null);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.