开发者

The ConnectionString property has not been initialized

开发者 https://www.devze.com 2023-01-13 19:15 出处:网络
My connection string is placed in web.config as follows. <connectionStrings> <add name=\"empcon\" connectionString=\"Persist Security Info=False;User ID=sa;Password=abc;Initial Catalog=db5pm

My connection string is placed in web.config as follows.

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

and the code of program is...

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.ConnectionStr开发者_C百科ings["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();
        }        

i am totally new to programing....

i am able to run this application with er.message in label control as "the connection string property has not been initialized"

i need to retrieve the list of names of employees from the emp table in database into the dropdownlist and show them to the user...

can any one please fix it...


Where are you initializing your constr variable? It looks like you can leave that line out.

Also: just use using

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

Side note: Don't use Select * From. Call out your columns: Select empname, empno From...


You are not assigning ConfigurationManager.ConnectionStrings["empcon"].ToString(); to string constr

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

will probably solve your problem for the time being.

0

精彩评论

暂无评论...
验证码 换一张
取 消