【发布时间】:2019-05-24 17:53:00
【问题描述】:
在我的按钮单击事件中,我想在表格中插入一行。当我单击按钮时,我没有例外,我也没有显示我的消息框。我有消息框作为检查查询是否已执行的一种方式。
当我单步执行时,它会跳过 MessageBox 并且不会引发异常。
private void BtnSend_Click(object sender, EventArgs e)
{
string theDate = dateTimePicker1.Value.ToString("MM-dd-yyyy");
var select = "INSERT INTO Trinity3(Date, Device_S_N, Student_Last_Name, Student_First_Name, Student_Number, School, Grade, Damage)" +
"VALUES (@Date, @Serial, @LastName, @FirstName, @StudentNum, @School, @Grade, @Damage)" +
"COMMIT";
SqlConnection connection = new SqlConnection("Data Source=CPS1113020004; Initial Catalog=Coweta Public Schools; Integrated Security=True");
// Create a SqlCommand instance
SqlCommand command = new SqlCommand(select, connection);
// Add the parameter
command.CommandType = CommandType.Text;
command.CommandText = select;
command.Parameters.AddWithValue("@Date", theDate);
command.Parameters.AddWithValue("@Serial",txtSerial.Text);
command.Parameters.AddWithValue("@LastName",txtLastName.Text);
command.Parameters.AddWithValue("@FirstName",txtFirstName.Text);
command.Parameters.AddWithValue("@StudentNum", txtStudentNum.Text);
command.Parameters.AddWithValue("@School",txtSchool.Text);
command.Parameters.AddWithValue("@Grade", txtGrade.Text);
command.Parameters.AddWithValue("@Damage", txtDamage.Text);
// Execute the query
try
{
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("Records inserted successfully");
}
catch
{
// Handle exception, show message to user...
}
finally
{
connection.Close();
}
this.Visible = false;
var searchForm = new SearchForm();
searchForm.ShowDialog();
}
【问题讨论】:
-
把
[Date]放在括号里。你的“日期”应该是一个日期,而不是一个字符串。不要认为你需要那条 COMMIT 行。 -
清理解决方案并确保您处于调试模式。然后构建并确保没有错误。
-
空的
Catch块永远不会报告问题。另外,AddWithValue是个坏主意 -
如何“跳过消息框”?如果执行该行代码,则会显示一个消息框。您确定自上次更改后您已完全重新构建代码?或者您的(空)
catch块没有被访问? -
你在 catch 部分什么都没有,异常可能被默默地忽略了。
标签: c# sql-server winforms