Click here to Skip to main content
15,910,797 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
What is wrong with my code? When Im setting up the connection between sql server management studio and c#, it gives me this error ExecuteNonQuery: Connection property has not been initialized.
private void button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection();
    con.ConnectionString= "Database= hotel; server= Roger\SQLEXPRESS";
    con.Open();
    SqlCommand cmd = new SqlCommand("insert into CheckIn (@TransactionId,@GuestName,@RoomType,@RoomNo,@ReservationDate,@CheckInDate,@CheckOutDate," + "@NoOfDays,@NoOfAdults,@NoOfChildren)");
    cmd.Parameters.AddWithValue("@TransactionId",textBox1.Text);
    cmd.Parameters.AddWithValue("@GuestName", textBox2.Text);
    cmd.Parameters.AddWithValue("@RoomType", textBox3.Text);
    cmd.Parameters.AddWithValue("@RoomNo", textBox4.Text);
    cmd.Parameters.AddWithValue("@ReservationDate", textBox5.Text);
    cmd.Parameters.AddWithValue("@CheckInDate", textBox6.Text);
    cmd.Parameters.AddWithValue("@CheckOutDate", textBox7.Text);
    cmd.Parameters.AddWithValue("@NoOfDays", textBox8.Text);
    cmd.Parameters.AddWithValue("@NoOfAdults", textBox9.Text);
    cmd.Parameters.AddWithValue("@NoOfChildren", textBox10.Text);

    cmd.ExecuteNonQuery();
    con.Close();
    MessageBox.Show("DATA ADDED SUCCESSFULLY!!");
Posted
Updated 28-May-13 11:40am
v2
Comments
Richard C Bishop 28-May-13 17:42pm    
You need to add the connection to your command. Add this:

SqlCommand cmd = new SqlCommand("insert into CheckIn (@TransactionId,@GuestName,@RoomType,@RoomNo,@ReservationDate,@CheckInDate,@CheckOutDate," + "@NoOfDays,@NoOfAdults,@NoOfChildren)", con);
Roger Buthello 28-May-13 18:04pm    
still da same error
Sergey Alexandrovich Kryukov 28-May-13 17:43pm    
Why do you call it "between SQL Server and C#"? Do you think C# sits in your process and do the connection? :-)
—SA
joshrduncan2012 28-May-13 18:00pm    
SA makes a good point. :)

I agree with Rich. Add the connection variable to the end of the command (as he pointed out) and you should be good to go.
Roger Buthello 28-May-13 18:04pm    
still da same error

1 solution

Try this format for your sql connection, fill in the blanks with your DB information:
SqlConnection con = new SqlConnection(@"Data Source='your pc name\SQLEXPRESS'; UserID=sa;Password=****;Initial Catalog='MyDatabase'; IntegratedSecurity=True;");
 
Share this answer
 
v4

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