问题
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
回答1:
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>
来源:https://stackoverflow.com/questions/22496236/cannot-connect-to-sql-server-due-to-nullreferenceexception