簡體   English   中英

ConnectionString屬性尚未初始化

[英]The ConnectionString property has not been initialized

我的連接字符串放在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表中檢索員工姓名列表到下拉列表中並將其顯示給用戶...

任何人都可以解決它...

你在哪里初始化你的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...

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

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

可能會暫時解決你的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM