Cannot connect to Sql server due to NullReferenceException [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have a windows forms application which begins with the Login form
The Login form has been fine for past few day while i was working on rest of the application
I get an error now that
I have two database one DB.mdf and one MYD.sdf
NullReferenceException was unhandled
Object reference not set to an instance of an object.
for this particular lines of code --- >
private void button1_Click(object sender, EventArgs e)
{
string path=#"C:\Users\Srinath\Documents\Visual Studio 2010\Projects\TESTFEE\TESTFEE\DB.mdf";
SqlConnection con =new SqlConnection(#"Data Source=.\SQLEXPRESS; AttachDbFilename='"+path+"';User Instance=True");
string constring=ConfigurationManager.ConnectionStrings["ConnectionStringFMS"].ConnectionString;
//SqlConnection con=new SqlConnection(constring);
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from LOGIN where USERNAME='" + textUser.Text + "' and PASSWORD='" + textPass.Text + "'", con);
DataTable dt = new DataTable();
try
{
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
e1.Show();
}
else
{
HoldButton();
MessageBox.Show("Please Enter Your Right Credentials");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}//![The error i get ][1 -]
I tried using the Configuration File for connection string
before i directly used the SqlConnection for connection
I am using Sql server 2008 r2 with the Management studio
I first recieved the Failed to connect to the default database inititally
Doubts - >
is it the Problem because of using two different types of db in one application
I tried reinstalling sql server 2008 but no use
please help

Put your connection string in webconfig, If you have the *.mdf placed in App_Data folder, using this format works
<connectionStrings>
<add name="ConnectionName"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>

Related

error 26- error locating server/instance specified

I designed a C# desktop app in visual studio 2019 and for database used sql server express 2019 edition. i am trying to run this app on another pc. i have installed sql server express 2019 in the other pc also MS server management studio 2019 installed and restored the database. everything works fine like login,saving updating,deleting but when i try to fetch data to datagridview it shows "system.data.sqlclient.sqlexception - a network related or instance specific error occurred while establishing a connection to sql server. the server was not found or was not accessible. verify instance name is correct and sql server is configured to allow remote connections.(provider: sql network interfaces, error: 26 - error locating server/instance specified)."
all the ports are enabled and firewall rule is also enabled in the client pc.
i am using the below connection string for the connection.
class Connection
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=icon;Integrated Security=True");
public SqlConnection active()
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
return con;
}
}
Please help anyone as i am not able to get what is the problem going on.
Belowcode is working
private void loginBtn_Click(object sender, EventArgs e)
{
Connection con = new Connection();
SqlCommand cmd = new SqlCommand("select * from [user] where
Username='" + usernameTxt.Text + "'and password='" + passwordTxt.Text
+ "'", con.active());
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login Successful", "Sucsess",
MessageBoxButtons.OK, MessageBoxIcon.Information);
new dashboard().Show();
this.Hide();
}
but this is not working.it shows the error when i try to fetch the data.
public partial class AllSudent : Form
{
public AllSudent()
{
InitializeComponent();
}
Connection con = new Connection();
public int studentID;
private void AllSudent_Load(object sender, EventArgs e)
{
GetStudentsRecord();
}
public void GetStudentsRecord()
{
SqlCommand cmd = new SqlCommand("Select * From [student]",
con.active());
DataTable dt = new DataTable();
SqlDataReader sdr = cmd.ExecuteReader();
dt.Load(sdr);
sdataGridView.DataSource = dt;
}
Throw your Connection class away, and pass the connection string to the DataAdapter. Don't bother opening or closing the connection; DataAdapter knows how to open a connection if it's closed
Put the connectionstring into the Settings
Use parameters
private void loginBtn_Click(object sender, EventArgs e)
{
using(var sda = new SqlDataAdapter("select * from [user] where Username=#user and password=#pass", Properties.Settings.Default.ConStr)
{
//USE PARAMETERS
sda.SelectCommand.Parameters.Add("#user", SqlDbType.VarChar, usernameTxt.Text.Length).Value = usernameTxt.Text;
sda.SelectCommand.Parameters.Add("#pass", SqlDbType.VarChar, passwordTxt.Text.Length).Value = passwordTxt.Text.GetHashcode(); //DO NOT store your passwords in plain text!!
var dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login Successful", "Sucsess",
MessageBoxButtons.OK, MessageBoxIcon.Information);
new dashboard().Show();
this.Hide();
}
}
}
Use parameters
Just in case you missed it: USE PARAMETERS. Never again, in your life ever, should you concatenate a value into an SQL string. Ever. There is no reason to do it, and doing it will result in the software you create being hacked / you getting fired / both
Also, don't store passwords in plain text, ever. Salt and hash them. I've used string.GetHashcode() for demo purposes, which is not good but better than plaintext
Do the same thing to the not working code:
public void GetStudentsRecord()
{
using(var sda = new SqlDataAdapter("Select * From [student]", Properties.Settings.Default.ConStr)){
var dt = new DataTable();
sda.Fill(dt);
sdataGridView.DataSource = dt;
}
}
this issue also confusing me a few days after the IT guy do some security settings to the SQL Server. i have an EntityFramework for the Web application and a desktop application. after i did some setting on the SQL Server, the Web application comeback to work, but the desktop still with issue. but i used the some connection string for the both application, it make no sense one is work but the other doesn't. then i searched a lot until i found some one said need add a port number 1433 after the $ServerName$DatabaseInstanceName,1433 at here http://www.windows-tech.info/15/9f6dedc097727100.php . after i added it. the exception became: System.Data.SqlClient.SqlException: Login failed for user 'domain\name-PC$'. then i found this link System.Data.SqlClient.SqlException: Login failed for user: System.Data.SqlClient.SqlException: Login failed for user it said need add Trusted_Connection=False;. the whole connection string should be like: data source=XXXXX\SQLSERVER,1433;initial catalog=XXXDB;user id=UserID;password=PWD;Trusted_Connection=False;MultipleActiveResultSets=True;
hope this answer will help the ones out off Generic exception: "Error: 26-Error Locating Server/Instance Specified)

Personalized database Connection string for C# application

I am trying to have a personalized database connection string for the machines i install the C# application into. I have created a database using Visual Studio but that only points the location of the database to my personal directory and that is not something general.
Now when i try to publish the application and try to install it in some other computer, the database gives me an error that it wasnt found, which makes sense because the connection string is pointing to my personal computers directory.
Here is part of my code:
private void button13_Click_1(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;");
sda = new SqlDataAdapter(#"SELECT [Panel Progress].*
FROM [Panel Progress]", con);
fill_grid();
}
catch (Exception error)
{
label6.Text = error.Message;
}
}
Can anyone please guide me towards the right path to solve this issue and to generate a personalized connection string for every computer the database gets installed to?
In your app.config or web.config file (Whichever is relevant to you) add the following connection string under configuration tag.
<connectionStrings>
<add name="DbConnection" connectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;" />
</connectionStrings>
If you already have a connection strings section then add only the
<add name="DbConnection" connectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;" />
Then in your C# code instead of hard coding the connection string you can use the config value.
string connectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
private void button13_Click_1(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(connectionString);
sda = new SqlDataAdapter(#"SELECT [Panel Progress].*
FROM [Panel Progress]", con);
fill_grid();
}
catch (Exception error)
{
label6.Text = error.Message;
}
}
Build it. Then when you deploy the application in to another machine all you have to do is change your connection string in the app.config or web.config(whichever is relevant for you) to the new file location without changing hard coded values and rebuilding the application again.

asp.net cannot open database login failed

I'm using the following to retrieve data from a database but the SqlConnection won't open. It throws an error at scon.Open(). I'm sure it's elementary but I can't work it out.
protected void Page_Load(object sender, EventArgs e) {
SqlConnection scon = new SqlConnection("Data Source = .\\SQLEXPRESS; Database = populate.mdf; Integrated Security = true; Initial Catalog = populate");
StringBuilder htmlString = new StringBuilder();
if(!IsPostBack)
{
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "SELECT * FROM populate";
scon.Open();
SqlDataReader articleReader = scmd.ExecuteReader();
htmlString.Append("'Populate page:'");
if (articleReader.HasRows)
{
while (articleReader.Read())
{
htmlString.Append(articleReader["dateTime"]);
htmlString.Append(articleReader["firstName"]);
htmlString.Append(articleReader["lastName"]);
htmlString.Append(articleReader["address"]);
htmlString.Append(articleReader["details"]);
}
populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() });
articleReader.Close();
articleReader.Dispose();
}
}
}
}
I'm using this link https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx as one of my references. I'm also using SQL Server 2008 R2 Express if these information are of any help.
Here's part of the error message:
SqlException (0x80131904): Cannot open database "populate" requested
by the login. The login failed.
Any help would be greatly appreciated.
Quoted from https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx#sse, if you want to use .mdf file as a database, you should use the following connection string containing AttacheDbFileName.
<add name="ConnectionStringName"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True" />
I solved it. All the connection string and other code was correct. The database just needed connecting to the Management Studio with some extra attention.

Connect to SQL Server 2008 Express database using C#

I am developing a Winforms application in which I am using SQL Server 2008 Express Edition as backend. But I am getting error:
Additional information: An attempt to attach an auto-named database for file D:\Hardik\Hardik\dotnet\TestApplication\TestApplication\bin\Debug\MyDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
My code is:
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Select * From MyTable";
cmd.CommandType = CommandType.Text;
da = new SqlDataAdapter();
da.SelectCommand = cmd;
dt = new DataTable();
ds = new DataSet();
da.Fill(ds, "Login");
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
}
and my app.config file is:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyConnection"
connectionString="Server=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True; User Instance=True"
providerName="System.Data.Client"/>
</connectionStrings>
</configuration>
Where I am wrong?
use double slash instend of single slash.
A UNC path uses double slashes or backslashes to precede the name of the computer.
<connectionStrings>
<add name="MyConnection" connectionString="Server=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True; User Instance=True" providerName="System.Data.Client"/>
</connectionStrings>
for instance failure
As you got the error "instance failure", that might be the error with your SQL Server instance..
Make sure your SQL Server instance(MSSQLSERVER) is running, where you can check in: Services list. TO get into services list: open run dialog box and type: "services.msc" (without quotes) and hit Enter. That takes you to services management console, where you can check whether your instance in running or not..
If the problem still persists, then try using: Data Source=.\SQLEXPRESS instead.. :)

App.config acts different than the regular way

My connection string used to be like this:
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=G:\I.S\C#\billingSystem\Store.mdf;Integrated Security=True;User Instance=True");
so i can (insert, update, delete) with this:
SqlCommand cmd = new SqlCommand("SQLSTATEMENT", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
I've seen a tutorial on youtube called "Deploy C# Project", when he used
System.Configuration;
and the app.config file, so I followed the tutorial exact the same way and it works.
The problem that after I (insert, update, delete) at runtime everything is okay until I close the application it's like I've did nothing at all the data that I've inserted is gone!.
I need to save the changes into the table at runtime.
Some info: Winforms app, sample from my code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="SchoolProjectConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\SchoolDB.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
namespace SchoolProject
{
public partial class Main : Form
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SchoolProjectConnectionString"].ToString());
public Main()
{
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
string myValue = Interaction.InputBox("Enter ID", "ID", "", 100, 100);
string myValue0 = Interaction.InputBox("Enter Name", "Name", "", 100, 100);
int X = Convert.ToInt32(myValue);
SqlCommand cmd = new SqlCommand("Insert into Student(ID, Student) Values ('" + X + "','" + myValue0 + "')", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
private void button2_Click(object sender, EventArgs e)
{
string myValue3 = Interaction.InputBox("Enter ID", "ID", "", 100, 100);
int X = Convert.ToInt32(myValue3);
SqlCommand cmd = new SqlCommand("SELECT * FROM Student WHERE id = '" + X + "'", cn);
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
MessageBox.Show(reader["Student"].ToString());
}
}
cn.Close();
}
private void button3_Click(object sender, EventArgs e)
{
Report R = new Report();
R.Show();
}
}
}
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. Store)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=Store;Integrated Security=True
and everything else is exactly the same as before...
Also: you should read up on SQL injection and change your code to avoid that - it's the #1 security risk for apps. You should use parametrized queries in ADO.NET instead - those are safe, and they're faster, too!

Categories