2017-10-08 257 views
0

請幫我解決這個問題: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);是觸發錯誤的行 –

回答

1

你有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上工作......非常感謝你 –

相關問題