Sorry but your code has many errors. Let me show a different approach
private void btnInsert_Click(object sender, EventArgs e)
{
string cnString = @"Data Source=DASTGIRKHAN\\SQLEXPRESS;
Initial Catalog=DBProject;
Integrated Security=True;";
string cmdText = @"Insert INTO EmployeeRecord
Values(@code,@fname,@cell,@adr)";
using(SqlConnection conn = new SqlConnection(cnString))
using(SqlCommand cmd = new SqlCommand(cmdText, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("@code", Convert.ToInt32(tfCode.Text));
cmd.Parameters.AddWithValue("@fname", tfName.Text );
cmd.Parameters.AddWithValue("@cell", tfCell.Text );
cmd.Parameters.AddWithValue("@adr", tfAdrs.Text);
int rowsInserted = cmd.ExecuteNonQuery();
if(rowInserted > 0)
MessageBox.Show("Inserted Successfully");
else
MessageBox.Show("Insert failes");
}
}
The primary cause of your error is stated by the answer of kmatyaszek, but this is just the tip of the iceberg.
You should always use the using statement around your disposable objects like the connection. This will ensure that the connection is closed and disposed also in case of exceptions.
You should use a parameterized query to create your command to avoid Sql Injection and parsing problems. For example, a single quote in the tfName
textbox could lead to a Syntax Error.
The call to BeginExecuteNonQuery
, excludes the call to ExecuteNonQuery
and requires a call to EndExecuteNonQuery
.
Finally, the result of ExecuteNonQuery
tells you if the insertion is successful.
As a last note, I have remove the Pooling=False
from the connection string.
You haven't said anything why do you want avoid his very useful optimization.