[英]ConnectionString property has not been initialized IN ASP.NET
Please help me solving this problem: 请帮助我解决这个问题:
The ConnectionString property has not been initialized.
ConnectionString属性尚未初始化。
I'm new to ASP.NET. 我是ASP.NET的新手。
I'm trying to display the username after log in in e Label1.Text
. 登录e
Label1.Text
后,我试图显示用户名。 But when I run the code, it shows this error... it also shows 但是当我运行代码时,它显示了此错误...
INVALID OPERATION EXCEPTION WAS UNHANDLED
无效的操作异常被阻止
My code: 我的代码:
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();
}
}
}
You have 2 different instances of SqlConnection
, both of them named con
. 您有2个不同的
SqlConnection
实例,两个实例均名为con
。
The first is declared in your class: 第一个在您的类中声明:
SqlConnection con = new SqlConnection();
The second is declared inside of Page_Load
: 第二个在
Page_Load
内部声明:
SqlConnection con = new SqlConnection("Data Source=BOW-PC\\BOW;Initial Catalog= BCHCS;Integrated Security=True");
When you call showdata()
, you are using the first instance, which has not been initialized. 调用
showdata()
,您正在使用的第一个实例尚未初始化。
You really should refactor this to use a single connection. 您确实应该重构它以使用单个连接。 Also, to ensure you don't have any resource leaks, it is important to use a using block on
SqlConnection
or call Dispose
in a finally block. 另外,为确保没有任何资源泄漏,在
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.