ConnectionString property has not been initialized IN ASP.NET - c#

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();
}
}
}

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();
}

Related

Inserting DropDownList item into SQL Database

I have a DropDownList which is populated with data from an SQL Table. Within the webform when users select an item from that list, i want it to insert the selected choice into another SQL table, everything works other than the DropDownLists
I've tried :
cmd.Parameters.AddWithValue("#*", ddl*.SelectedValue);
cmd.Parameters.AddWithValue("#*", ddl*.SelectedItem.Text);
etc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Data;
using System.Configuration;
using System.Text;
using System.Drawing;
namespace VXUK2
{
public partial class booking_system : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// SQL Query For DropDownList1 (CIT Company)
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\****;Persist Security Info=True;User ID=***;Password=****;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand("Select CIT_ID, CIT_CompanyName from CIT_Details", con);
ddlCITCompany.DataSource = cmd.ExecuteReader();
ddlCITCompany.DataTextField = "CIT_CompanyName";
ddlCITCompany.DataValueField = "CIT_ID";
ddlCITCompany.DataBind();
// SQL Query for DropDownList2 (Site Details)
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = ("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\***;Persist Security Info=True;User ID=***;Password=****;Connect Timeout=30");
con2.Open();
SqlCommand cmd2 = new SqlCommand("Select Site_ID, Site_Name from Site_Details", con2);
ddlVisitingCentre.DataSource = cmd2.ExecuteReader();
ddlVisitingCentre.DataTextField = "Site_Name";
ddlVisitingCentre.DataValueField = "Site_ID";
ddlVisitingCentre.DataBind();
}
protected void Submit2_Click(object sender, EventArgs e)
{
//LocalDB Connection & Execution String
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\***;Persist Security Info=True;User ID=***;Password=****;Connect Timeout=30");
con.Open();
String st = "INSERT INTO Booking_Data (Visiting_Centre, Expected_Arrival_Date, Expected_Arrival_Time, Actual_Arrival_Date, Actual_Arrival_Time, CIT_Company, Driver_Name, Vehicle_Registration, Supplied_Password, Delivery_In, Delivery_Out, Time_Booked_In, Time_Booked_Out) values (#Visiting_Centre, #Expected_Arrival_Date, #Expected_Arrival_Time, #Actual_Arrival_Date, #Actual_Arrival_Time, #CIT_Company, #Driver_Name, #Vehicle_Registration, #Supplied_Password, #Delivery_In, #Delivery_Out, #Time_Booked_In, #Time_Booked_Out)";
SqlCommand cmd = new SqlCommand(st, con);
cmd.Parameters.AddWithValue("#Visiting_Centre", ddlVisitingCentre.SelectedValue);
cmd.Parameters.AddWithValue("#Expected_Arrival_Date", txtExpectedArrivalDate.Text);
cmd.Parameters.AddWithValue("#Expected_Arrival_Time", txtExpectedArrivalTime.Text);
cmd.Parameters.AddWithValue("#Actual_Arrival_Date", txtActualArrivalDate.Text);
cmd.Parameters.AddWithValue("#Actual_Arrival_Time", txtActualArrivalTime.Text);
cmd.Parameters.AddWithValue("#CIT_Company", ddlCITCompany.SelectedValue);
cmd.Parameters.AddWithValue("#Driver_Name", txtDriverName.Text);
cmd.Parameters.AddWithValue("#Vehicle_Registration", txtVehicleRegistration.Text);
cmd.Parameters.AddWithValue("#Supplied_Password", txtSuppliedPassword.Text);
cmd.Parameters.AddWithValue("#Delivery_In", txtDeliveryIn.Text);
cmd.Parameters.AddWithValue("#Delivery_Out", txtDeliveryOut.Text);
cmd.Parameters.AddWithValue("#Time_Booked_In", txtTimeBookedIn.Text);
cmd.Parameters.AddWithValue("#Time_Booked_Out", txtTimeBookedOut.Text);
cmd.ExecuteNonQuery();
con.Close();
You have to add not isPostBack as every time any function called it reloads the Entire web-page, So every time you can see the first data is selected.
By Adding !IsPostBack the Page will not Re-Load Data Implicitly.
This can Solve your Problem in Selecting Data.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Your Code
}
}

Basic ASP Search SQL Server with a datagrid

im trying to follow a basic asp.net videos: https://www.youtube.com/watch?v=9e0kwADEoEg to create a web page that has a textbox, button and gridview.
For some reason the gridview will never show with populated data :/ I think its because of the .fill but really not sure. I can see the query when running a trace on sql server. just no output on the webpage!? Can anyone assist?
ausing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection vid = new SqlConnection("Server=localhost;Database=exam;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string str = "select F1,F2,F3,F4 from [dbo].[CandDbase] Where F4 = '#search'";
SqlCommand xp = new SqlCommand(str,vid);
xp.Parameters.Add("#search", SqlDbType.NVarChar).Value = TextBox1.Text;
vid.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
GridView1.DataSource = ds;
GridView1.DataBind();
vid.Close();
}
}
Get rid of the single quotes in the query:
string str = "select F1,F2,F3,F4 from [dbo].[CandDbase] Where F4 = #search";
The quotes tell Sql Server to treat #search as a string literal instead of an sql variable name.
Additionally, get rid of the ExecuteNonQuery() code. That function is for INSERT/UPDATE/DELETE statements.
Another issue is the SqlConnection object. Don't try to re-use the SqlConnection object in your page. .Net uses a feature called connection pooling to cache the underlying connection object, and trying to re-use the same .Net SqlConnection object instance conflicts with that. Just keep the connection string handy and create a new SqlConnection instance. Really.
There's more, too. The code below makes a number of other improvements: using so things are cleaned up in case of an exception, Fill() will open and close the connection for you, binding to a specific table, etc...
private const string cnString = "Server=localhost;Database=exam;Integrated Security=True";
protected void Button1_Click(object sender, EventArgs e)
{
string sql = "select F1,F2,F3,F4 from [dbo].[CandDbase] Where F4 = #search";
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(cnString))
using (SqlCommand xp = new SqlCommand(sql, con))
using (SqlDataAdapter da = new SqlDataAdapter(xp))
{
xp.Parameters.Add("#search", SqlDbType.NVarChar).Value = TextBox1.Text;
da.Fill(ds, "Name");
}
GridView1.DataSource = ds.Tables["Name"];
GridView1.DataBind();
}
// Open connection
using (SqlConnection c = new SqlConnection(vid))
{
c.Open();
// 2
// Create new DataAdapter
using (SqlDataAdapter a = new SqlDataAdapter(
"SELECT * FROM EmployeeIDs", c))
{
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// 4
// Render data onto the screen
dataGridView1.DataSource = t; // <-- From your designer
}
}

Database connection string

I'm just trying create and write to the database file.
I don't know why connection string has turned such:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\Documents\DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30
With this connection string, I get this error:
Error CS1009 Unrecognized escape sequence
XXX_DATABASE_TEST D:\FOLDER\XXX_DATABASE_TEST\Form1.cs
So I've changed "/" to "\":
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:/Users/User/Documents/DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30
Error has gone, form loads, but database is empty, doesn't writes. Can you help me figure out, what I'm doing wrong here:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace XXX_DATABASE_TEST
{
public partial class Form1 : Form
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\Documents\DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
cmd = new SqlCommand("INSERT INTO testdata VALUES (Name, IDo, Gender) VALUES (#Name,#IDo,#Gender)", con);
cmd.Parameters.Add("#Name", textBox1.Text);
cmd.Parameters.Add("#IDo", textBox1.Text);
cmd.Parameters.Add("#Gender", comboBox1.SelectedItem.ToString());
cmd.ExecuteNonQuery();
}
}
}
I think your connection string have to be like this :
con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\User\\Documents\\DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30");
And for localdb, you can do something like this too :
con = new SqlConnection("Data Source = .;Initial Catalog = DATA_TEST;Integrated Security = True")

how to insert data into sql server in asp.net website?

I tried to insert data into sql server from my website build in vs 2008.For that I used button click event .I tried code shown in youtube but the code doesn't work .It shows error in my website.
The code in .aspx.cs file is
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
conn.Open();
}
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Insert values('"+txtCity.Text+"','"+txtFName.Text+"','"+txtLName.Text+"')",conn);
cmd.ExecuteNonQuery();
conn.Close();
Label1.Visible =true;
Label1.Text = "Your data inserted successfully";
txtCity.Text = "";
txtFName.Text = "";
txtLName.Text = "";
}
}
`
Okay, let's fix this code up just a little. You're getting there:
var cnnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var cmd = "insert into Insert values(#City,#FName,#LName)";
using (SqlConnection cnn = new SqlConnection(cnnString))
{
using (SqlCommand cmd = new SqlCommand(cmd, cnn))
{
cmd.Parameters.AddWithValue("#City",txtCity.Text);
cmd.Parameters.AddWithValue("#FName",txtFName.Text);
cmd.Parameters.AddWithValue("#LName",txtLName.Text);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
A couple things to note about the modified code.
It's leveraging the using statement to ensure that resources are properly disposed.
It's parameterized to ensure that SQL Injection isn't a possibility.
It's not storing a connection object anywhere, get rid of that stored connection.
**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=mrinmoynandy;User ID=**;Password=****");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SumbitBtn_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into streg(Name,Father,Mother,Dob,Sex,Category,Maritial,Vill,Po,Ps,Dist,State,Pin,Country) values (#name,#father,#mother,#dob,#sex,#category,#maritial,#vill,#po,#ps,#dist,#state,#pin,#country)", con);
cmd.Parameters.AddWithValue(#"name", StNumTxt.Text);
cmd.Parameters.AddWithValue(#"father", FatNumTxt.Text);
cmd.Parameters.AddWithValue(#"mother", MotNumTxt.Text);
cmd.Parameters.AddWithValue(#"dob", DobRdp.SelectedDate);
cmd.Parameters.AddWithValue(#"sex", SexDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"category", CategoryDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"maritial", MaritialRbl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"vill", VillTxt.Text);
cmd.Parameters.AddWithValue(#"po", PoTxt.Text);
cmd.Parameters.AddWithValue(#"ps", PsTxt.Text);
cmd.Parameters.AddWithValue(#"dist", DistDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"state", StateTxt.Text);
cmd.Parameters.AddWithValue(#"pin", PinTxt.Text);
cmd.Parameters.AddWithValue(#"country", CountryTxt.Text);
con.Open();
con.Close();
}
}
Thanks
Mrinmoy Nandy
Phone No.: +91 9800451398
**
Creating procedure will avoid sql injection.
SQL
Create procedure insert
(#City,#FirstName,#LastName)
{
insert into tablename (City,FName,LName)
values(#City,#FirstName,#LastName)
}
C#
SqlConnection con=new sqlconnection("give ur connection string here");
sqlcommand cmd=new sqlcommand();
con.open();
cmd=new sqlcommand("insert",con);
cmd.commandtype=commandtype.storedprocedure;
cmd.parameters.addwithvalue("#City",txtCity.text);
cmd.parameters.addwithvalue("#FName",txtFName.text);
cmd.parameters.addwithvalue("#LNAme",txtLName.text);
cmd.ExecuteNonQuery();
con.close();

Error - A field initializer cannot reference the non-static field, method, or property

I have started today to learn about the SQL connection in C# programming. And I tried some basic thing like the Insert, Delete etc.
And I wanted to try the same thing in another project but I have a problem. Because It shows me an error that I can't solve :(
Error:
A field initializer cannot reference the non-static field, method, or property 'Artikujt.Form1.con'.
Here is my code (I just started to connect it with the Database in SQL)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Artikujt
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Data Source=TALY-PC;Initial Catalog=Katalogi;Integrated Security=True;Pooling=False");
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tblArtikujt", con);
DataSet dsl = new DataSet();
public Form1()
{
InitializeComponent();
}
}
}
The error is in this code at the variable con
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tblArtikujt", con);
I created the Database in SQL (in Visual Studio)... I also added the Data Source. I did the exact thing that I did before.... but it isn't working :(
The error is exactly what it says. You cannot use con in your initialization of da because it will only be created during an instance creation. You will need to create con as static or put your initialization lines in your constructor.
HOWEVER, you should probably not do this in practice as you are just asking for somebody to open a SqlConnection and leave it open. You should probably fall more into the practice of creating your connections using a using block to take advantage of the disposing pattern
Static:
public partial class Form1 : Form
{
static SqlConnection con = new SqlConnection(#"Data Source=TALY-PC;Initial Catalog=Katalogi;Integrated Security=True;Pooling=False");
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tblArtikujt", con);
DataSet dsl = new DataSet();
public Form1()
{
InitializeComponent();
}
Or instantiation in the constructor:
public partial class Form1 : Form
{
SqlConnection con;
SqlDataAdapter da;
DataSet dsl;
public Form1()
{
InitializeComponent();
con = new SqlConnection(#"Data Source=TALY-PC;Initial Catalog=Katalogi;Integrated Security=True;Pooling=False");
da = new SqlDataAdapter("SELECT * FROM tblArtikujt", con);
dsl = new DataSet();
}
}
I will let you research the using block yourself
You'll need to move this initialization into the constructor.
SqlConnection con;
SqlDataAdapter da;
DataSet dsl;
public Form1()
{
InitializeComponent();
con = new SqlConnection(#"Data Source=TALY-PC;Initial Catalog=Katalogi;Integrated Security=True;Pooling=False");
da = new SqlDataAdapter("SELECT * FROM tblArtikujt", con)
dsl = new DataSet();
}
You must put your initialization code inside the constructor:
public partial class Form1 : Form
{
SqlConnection con = null;
SqlDataAdapter da = null;
DataSet dsl = null;
public Form1()
{
InitializeComponent();
con = new SqlConnection(#"Data Source=TALY-PC;Initial Catalog=Katalogi;Integrated Security=True;Pooling=False");
da = new SqlDataAdapter("SELECT * FROM tblArtikujt", con);
dsl = new DataSet();
}
}
You can not access con in the field initializer SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tblArtikujt", con); cause it's not static. The error is self explanatory. The issue is not SQL related it is c# related, I would recomment to revisit the C#.
static SqlConnection con = new SqlConnection(#"Data Source=TALY-PC;Initial Catalog=Katalogi;Integrated Security=True;Pooling=False");
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tblArtikujt", con);
DataSet dsl = new DataSet();
public Form1()
{
InitializeComponent();
}
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tblArtikujt", con);
use inside any method or event
like as bellow example button event
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Artikujt
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Data Source=TALY-PC;Initial Catalog=Katalogi;Integrated Security=True;Pooling=False");
DataSet dsl = new DataSet();
public Form1()
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tblArtikujt", con);
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{ SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tblArtikujt", con);
}
}
}

Categories

Resources