两次单击按钮的错误消息为:
附加信息:类型为System.Windows.Controls.TextBox的成员Id不能用作参数值
private void Button_Click(object sender, RoutedEventArgs e)
{
var connection = new SqlConnection(sqlConnectionString);
Student student = new Student();
connection.Open();
var affectedRows = connection.Execute("Delete from Student Where Id = @Id", new { Id = txtStudentID });
connection.Close();
//return affectedRows;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var connection = new SqlConnection(sqlConnectionString);
Student student = new Student();
var affectedRows = connection.Execute("Update Student set Name = @Name, Marks = @Marks Where Id = @Id", new { Id = txtStudentID, Name = txtName.Text, Marks = txtMarks.Text });
connection.Close();
}
您需要将文本框内的Text作为参数值发送,而不是发送textbox本身
connection.Execute(
"Delete from Student Where Id = @Id",
new { Id = txtStudentID.Text }
// ^^^^^
);
最好不要要求SQL Server进行数据转换。如果数据库中的ID列是整数,则将字符串解析为C#端的整数:
connection.Execute(
"Delete from Student Where Id = @Id",
new { Id = int.Parse(txtStudentID.Text) }
);
或者使用NumericUpDown控件,这样您就不必担心解析失败(只能输入数字(
connection.Execute(
"Delete from Student Where Id = @Id",
new { Id = (int)nudStudentID.Value }
);
类似地,如果ID是例如Guid,则解析它。
更新查询也有同样的建议-名称和标记上有.Text
(它是数字?请参阅上面的解析建议(,但ID上没有;可能是复制错误
其他建议:
您应该编写using var
来创建连接。你不需要培养一个新学生。Dapper将打开/关闭已关闭的连接。它将打开由您打开的连接。您不使用受影响的行,因此不需要捕获它:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
using var connection = new SqlConnection(sqlConnectionString);
connection.Execute(
"Update Student set Name = @Name, Marks = @Marks Where Id = @Id",
new {
Id = int.Parse(txtStudentID.Text),
Name = txtName.Text,
Marks = double.Parse(txtMarks.Text)
}
);
}
txtStudentID是控件吗?如果是,则应使用txtStudentID的Text属性。如果是数字数据类型,则可以尝试.ToString((it.