Object reference not set to an instance of an object

Posted by M3nhaq under C# on 10/27/2011 | Points: 10 | Views : 1906 | Status : [Member] | Replies : 2
Kindly tell me what`s wrong with this code. I am inserting data in data base using two input fields EndValueTextBox and StartValueTextBox .

I am receiving following error. "Object reference not set to an instance of an object"

private void buttonSave_Click(object sender, EventArgs e)
{
connection = new System.Data.SqlClient.SqlConnection();
da = new SqlDataAdapter();
try
{
connection.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message,"Connection String");
}
try
{
connection.Open();
string sql = "insert into TBLWORKERS (first_name , last_name )" + " values('" + StartValueTextBox.Text + "', '" + EndValueTextBox.Text + ")";
//SqlDataAdapter da = new SqlDataAdapter(query, connString);


da.InsertCommand.CommandText = sql;

da.InsertCommand.ExecuteNonQuery();

}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Connection open");
}


}





Responses

Posted by: Abdulhaknet on: 10/27/2011 [Member] Starter | Points: 25

Up
0
Down
Hi friend,

I think that there may be exception raice in first try block for this connection string is not set. and come to second it gives arror of Object reference error.

Please try the connection string as follow

SqlConnection connection = new SqlConnection (@"Data Source=.\SQLEXPRESS; Integrated Security=True;"+
@"AttachDbFilename=G:\C#.Net\Forms Practice\WindowsFormsPractice1\WindowsFormsPractice1\WindowsFormsPractice1.mdf;Initial Catalog=WindowsFormsPractice1");

Regards,

Abdul Hak.

M3nhaq, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: M3nhaq on: 10/27/2011 [Member] Starter | Points: 25

Up
0
Down
Asslam O Alikum!

Abdul Hak thanks for reply. I change the string but it came with an other error.
As I am using Win7 so I apply following code

SqlConnection connection = new SqlConnection(@"Data Source=.\\SQLEXPRESS; Integrated Security=True;" + @"AttachDbFilename=G:\\C#.Net\\Forms Practice\\WindowsFormsPractice1\\WindowsFormsPractice1\\WindowsFormsPractice1.mdf;Initial Catalog=WindowsFormsPractice1");


I get following error. "Instance Failure"

When I apply this code
 SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS; Integrated Security=True;" + @"AttachDbFilename=G:\C#.Net\Forms Practice\WindowsFormsPractice1\WindowsFormsPractice1\WindowsFormsPractice1.mdf;Initial Catalog=WindowsFormsPractice1");


I got following error

 Download source file

M3nhaq, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response