I'm a beginner, and new to C#, I don't know how to fix this bug, please help SQL Service is running, VS2019 is updated to the newest and I am Windows 10. It only said Exception thrown:
'System.Data.SqlClient.SqlException' in System.Data.dll
Here's my code :
private void btnInsert_Click(object sender, EventArgs e)
{
conn = new SqlConnection(@"Data Source=TS-G5\SQLEXPRESS;Initial Catalog=EsoftProj;Integrated Security=True");
cmd = new SqlCommand("INSERT INTO SES (Registration Number, Student Name, Date of Birth, Gender, Contact Number, Course enrolled in) VALUES (@Registration Number, @Student Name, @Date of Birth, @Gender, @Contact Number, @Course enrolled in)", conn);
conn.Open();
cmd.Parameters.Add("@Registration Number", SqlDbType.Text).Value = RegNumTB.Text;
cmd.Parameters.Add("@Student Name", SqlDbType.Text).Value = StudentNameTB.Text;
cmd.Parameters.Add("@Date of Birth", SqlDbType.Date).Value = DoBPick.Value.Date;
cmd.Parameters.Add("@Gender", SqlDbType.Text).Value = GMale.Checked ? "Male" : "Female";
cmd.Parameters.Add("@Contact Number", SqlDbType.Text).Value = ContactNumTB.Text;
cmd.Parameters.Add("@Course enrolled in", SqlDbType.Text).Value = CourseEnrSel.GetItemText(CourseEnrSel.SelectedItem);
cmd.ExecuteNonQuery();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
Most programming languages, including C# and SQL, don't like spaces inside identifiers.
In SQL Server you can get around that using
[]
. but I'm not sure about the parameters, best to avoid spaces there.