2010-08-26 256 views
4

我的連接字符串放置在web.config中,如下所示。ConnectionString屬性尚未初始化

<connectionStrings> 
    <add name="empcon" connectionString="Persist Security Info=False;User ID=sa;Password=abc;Initial Catalog=db5pmto8pm;Data Source=SOWMYA-3BBF60D0\SOWMYA" /> 
</connectionStrings> 

和程序的代碼...

public partial class empoperations : System.Web.UI.Page 
{ 

    string constr = null; 

    protected void Page_Load(object sender, EventArgs e) 

    { 
     ConfigurationManager.ConnectionStrings["empcon"].ToString(); 
     if (!this.IsPostBack) 
     { 
      fillemps(); 
     } 
    } 
    public void fillemps() 
    { 
     dlstemps.Items.Clear(); 
     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["empcon"].ConnectionString); 
     con.ConnectionString = constr; 
     SqlCommand cmd = new SqlCommand(); 
     cmd.CommandText = "select * from emp"; 
     cmd.Connection = con; 
     SqlDataReader reader; 
     try 
     { 
      con.Open(); 
      reader = cmd.ExecuteReader(); 
      while (reader.Read()) 
      { 
       ListItem lt = new ListItem(); 
       lt.Text = reader["ename"].ToString(); 
       lt.Value = reader["empno"].ToString(); 
       dlstemps.Items.Add(lt); 
      } 
      reader.Close(); 
     } 
     catch (Exception er) 
     { 
      lblerror.Text = er.Message; 
     } 
     finally 
     { 
      con.Close(); 
     }   

我完全新的編程....

我能夠在標籤er.message運行此應用程序控制爲「連接字符串屬性尚未初始化」

我需要從數據庫的emp表中檢索僱員的姓名列表到下拉列表中並將其顯示給用戶...

任何一個可以請修復它...

回答

1

您還沒有分配到ConfigurationManager.ConnectionStrings["empcon"].ToString();string constr

protected void Page_Load(object sender, EventArgs e) 
{ 
    constr = ConfigurationManager.ConnectionStrings["empcon"].ToString(); 
    ... 

可能會解決您的問題暫且。

+0

或者他可以刪除con.Connection = constr;行,這是從連接對象中刪除連接字符串。 – 2010-08-26 14:23:04

+0

hafalir 非常感謝...其固定的... – sowmya 2010-08-26 14:51:19

+1

@sowmya偉大 - 那麼你應該打勾最有幫助的答案接受它:http://stackoverflow.com/faq#howtoask謝謝! – Rup 2010-08-26 18:43:08

4

你在哪裏初始化的變量constr?看起來你可以離開這條線。

另外:只使用using

using(SqlConnection con = new SqlConnection(
    ConfigurationManager.ConnectionStrings["empcon"].ConnectionString) 
{ 
    using(SqlCommand cmd = new SqlCommand()) 
    { 
     cmd.Connection = con; 
     //Rest of your code here 
    } 
} 

邊注:請不要使用Select * From。召喚出你的專欄:Select empname, empno From...

+0

爲什麼選擇投票? – AllenG 2010-08-26 14:04:15

+0

你也可以使用'SqlCommand cmd = con.CreateCommand()'來創建連接預填充的'SqlCommand'(或者你的連接的正確類型變體)。然後你必須單獨設置SQL文本,而如果你使用'new SqlCommand()',你也可以將SQL傳遞給構造函數。 – Rup 2010-08-26 14:07:55

相關問題