ConnectionString属性尚未初始化。

5

我的连接字符串放在web.config文件中,如下所示。

<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表中检索员工姓名列表,并将它们显示在下拉列表中供用户选择...

请问有人能够修复这个问题吗?

2个回答

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...


你也可以使用 using(SqlCommand cmd = con.CreateCommand()) 来创建一个已经预先填充了连接的 SqlCommand(或者适用于你的连接的正确类型变量)。然后,你需要单独设置 SQL 文本,而如果你使用 new SqlCommand(),你也可以将 SQL 传递到构造函数中。 - Rup

1

您没有将 ConfigurationManager.ConnectionStrings["empcon"].ToString(); 赋值给 string constr

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

暂时可能会解决您的问题。


或者他可以删除 con.Connection = constr; 这一行,这会将连接字符串从 Connection 对象中移除。 - Jason Berkan
1
@sowmya 很好 - 那么你应该勾选最有帮助的答案来接受它:http://stackoverflow.com/faq#howtoask 谢谢! - Rup

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接