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

问题描述:

请帮我解决这个问题:ConnectionString属性尚未初始化在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(); 
     } 
    } 
} 
+1

您会在哪一行发生错误?你确定这是触发错误的代码吗? – Steve

+0

肯定不是触发错误的行。 – OctoCode

+0

对不起,我编辑了代码...我添加了showdata()方法... sda.Fill(ds);是触发错误的行 –

你有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上的使用块或在finally块中调用Dispose非常重要。

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

    showdata(); 
} 
+0

非常感谢你的工作......我设法在登录后显示用户的名字......我没有使用使用块就像你提到的那样在sqlConnection上工作......非常感谢你 –