Reputation: 33
Please help me solving this problem:
The ConnectionString property has not been initialized.
I'm new to ASP.NET.
I'm trying to display the username after log in in 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();
}
}
}
Upvotes: 0
Views: 2223
Reputation: 56849
You have 2 different instances of SqlConnection
, both of them named con
.
The first is declared in your class:
SqlConnection con = new SqlConnection();
The second is declared inside of 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.
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.
using (con = new SqlConnection("Data Source=BOW-PC\\BOW;Initial Catalog= BCHCS;Integrated Security=True"))
{
con.Open();
showdata();
}
Upvotes: 1