繁体   English   中英

未在ASP.NET中初始化ConnectionString属性

[英]ConnectionString property has not been initialized IN ASP.NET

请帮助我解决这个问题:

ConnectionString属性尚未初始化。

我是ASP.NET的新手。

登录e Label1.Text后,我试图显示用户名。 但是当我运行代码时,它显示了此错误...

无效的操作异常被阻止

我的代码:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Botswna_Centralized_Health_Card_System.healthcareOfficerLogins
{
    public partial class healthcareOfficerLogins : System.Web.UI.Page
    {
        SqlCommand cmd = new SqlCommand();
        SqlConnection con = new SqlConnection();
        SqlDataAdapter sda = new SqlDataAdapter();

        DataSet ds = new DataSet();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["hospital_name"] == null)
            {
                Response.Redirect("~/hospital_login/hospital_login.aspx");
            }
            else
            {
                SqlConnection con = new SqlConnection("Data Source=BOW-PC\\BOW;Initial Catalog= BCHCS;Integrated Security=True");
                con.Open();

                showdata();
            }
        }

        public void showdata()
        {
            cmd.CommandText="select * from hospitallogins where hospital_Name='" + Session["hospital_Name"]+ "'";
            cmd.Connection = con;
            sda.SelectCommand = cmd;

            sda.Fill(ds);
            Label1.Text= ds.Tables[0].Rows[0]["hospital_Name"].ToString();
        }
    }
}

您有2个不同的SqlConnection实例,两个实例均名为con

第一个在您的类中声明:

SqlConnection con = new SqlConnection();

第二个在Page_Load内部声明:

SqlConnection con = new SqlConnection("Data Source=BOW-PC\\BOW;Initial Catalog= BCHCS;Integrated Security=True");

调用showdata() ,您正在使用的第一个实例尚未初始化。

您确实应该重构它以使用单个连接。 另外,为确保没有任何资源泄漏,在SqlConnection上使用using块或在finally块中调用Dispose也很重要。

using (con = new SqlConnection("Data Source=BOW-PC\\BOW;Initial Catalog= BCHCS;Integrated Security=True"))
{
    con.Open();

    showdata();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM