C# 尚未在ASP.NET中初始化ConnectionString属性
请帮我解决这个问题: ConnectionString属性尚未初始化 我是ASP.NET新手 登录eC# 尚未在ASP.NET中初始化ConnectionString属性,c#,asp.net,C#,Asp.net,请帮我解决这个问题: ConnectionString属性尚未初始化 我是ASP.NET新手 登录eLabel1.Text后,我试图显示用户名。但是当我运行代码时,它显示了这个错误。。。它还显示了 未处理无效的操作异常 我的代码: using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; u
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();
}
}
}
您有两个不同的SqlConnection
实例,它们都名为con
第一个是在类中声明的:
SqlConnection con = new SqlConnection();
第二个在页面加载中声明:
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();
}
你在哪一行得到错误?您确定这是触发错误的代码吗?确定这不是触发错误的行。抱歉,我编辑了代码…我添加了showdata()方法…sda.Fill(ds);是触发错误的行。有两个“SqlConnection con”声明。全局和局部已删除本地sqlConnection con声明…但仍然有相同的错误非常感谢它的工作…我在登录后设法显示了一个用户名。。。正如您提到的,我确实在sqlConnection上使用了一个using块,并且工作正常……非常感谢