2013-03-28 15 views
2

我在我的數據庫中有一列「Klantnummer」和
我希望將該值作爲我的標籤文本。
我該怎麼做?如何使用數據庫中的值設置我的標籤文本?

protected string conS = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Databees.mdf;Integrated Security=True;User Instance=True"; 
protected SqlConnection con; 

protected void Page_Load(object sender, EventArgs e) 
{ 
    con = new SqlConnection(conS); 
    try 
    { 
     con.Open(); 
     string q = "SELECT * FROM tblKLanten;"; 
     SqlCommand query = new SqlCommand(q, con); 
     SqlDataReader dr = query.ExecuteReader(); 
     Label1.Text = ; //I want here the value of klantnummer 
     con.Close(); 
    } 
    catch (Exception ex) 
    { 
     Label2.Text = "Error"; 
    } 
} 

回答

1

你可以使用:

label1.Text = dr["Klantnummes"].ToString(); 
1

那麼,與所提供的信息是不太容易回答,但讓我們假設你的結構是這樣的:

CREATE TABLE tblKLanten (
    ID INT, 
    Klantnummer VARCHAR(50) 
) 

你需要從這樣的讀者的索引得到領域:

Label1.Text = dr.GetString(1); 

,但你也將需要閱讀,因此,您需要設置標籤之前發出這樣一句話:

bool success = dr.Read(); 
if (success) 
{ 
    // set the label in here 
} 

但要記住,它是基於關閉指數的在返回的語句等列,因爲你發出SELECT *我沒有辦法知道索引是什麼。最後,我建議做一些更多的變化,所以考慮下面的代碼:

protected string conS = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Databees.mdf;Integrated Security=True;User Instance=True"; 
protected SqlConnection con; 

protected void Page_Load(object sender, EventArgs e) 
{ 
    con = new SqlConnection(conS); 
    try 
    { 
     con.Open(); 
     string q = "SELECT * FROM tblKLanten;"; 
     SqlCommand query = new SqlCommand(q, con); 

     using (SqlDataReader dr = query.ExecuteReader()) 
     { 
      bool success = dr.Read(); 
      if (success) 
      { 
       Label1.Text = dr.GetString(1); 
      } 
     } 

     con.Close(); 
    } 
    catch (Exception ex) 
    { 
     Label2.Text = "Error"; 
    } 
} 

using聲明會有確保該SqlDataReader得到妥善處置。

相關問題