Click here to Skip to main content
15,904,288 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have created a table Employeetable that have 4 fields. I want to insert the value in table .
my code is as follows:

C#
SqlConnection connection1 = new SqlConnection();
          SqlCommand Insert = new SqlCommand();
          connection1.ConnectionString = (@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Acer\Documents\employeeDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
          int a = Convert.ToInt32(txtEmpId.Text);
          string b = txtEmpName.Text;
          int c = Convert.ToInt32(txtSalary.Text);
          string d = txtCity.Text;
          Insert.CommandText = "INSERT INTO Employeetable(EmpId,EmpName,Salary,City) Values (@a,@b,@c,@d)";
          Insert.Parameters.AddWithValue("@a", a);
          Insert.Parameters.AddWithValue("@b", b);
          Insert.Parameters.AddWithValue("@c", c);
         Insert.Parameters.AddWithValue("@d", d);
          Insert.Connection.Open();
          Insert.ExecuteNonQuery();
         Insert.Connection.Close();
          Response.Write("you have succesfully inserted data");

also when i debug it on insert.connection.open() debugger points object refrence not set to instance of object. where i am wrong? please help me. Thanks.
Posted
Updated 31-May-13 1:59am
v3
Comments
ZurdoDev 31-May-13 7:59am    
You have not set the connection property on your sqlcommand

You need to set the Connection property on your SqlCommand. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx[^]

For example,

C#
Insert.Connection = connection1;
 
Share this answer
 
here add this code to your project

 Insert.CommandText = "INSERT INTO Employeetable(EmpId,EmpName,Salary,City) Values (@a,@b,@c,@d)";
Insert.connection= connection1; //name instance of your sql connection; 


Why write two lines?? here the easy way:

string st="INSERT INTO Employeetable(EmpId,EmpName,Salary,City) Values (@a,@b,@c,@d";
//now declare your sql command
sql command insert= new sql command(st,connection1);

//or

sql command insert = new sql command("INSERT INTO Employeetable(EmpId,EmpName,Salary,City) Values (@a,@b,@c,@d", connection1)


You must associate your command to the connection one way or other!!!

:)

for assistance on retrieving visit
sql express
 
Share this answer
 
v2
Comments
Rambo_Raja 31-May-13 8:33am    
to fetch the respective values back on form what can i do? i.e to get empid,name,salary,city back what to do.i am not using ms mgmt studio . i have created my table in vs 2008 only. so can't use select query to check whether my values are insertted or not.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900