【发布时间】:2013-10-16 16:17:41
【问题描述】:
我正在 Winforms 中向数据库添加、删除和更新数据。我在所有添加、删除和更新表单上都有 gridview。 单击“删除”按钮删除记录后,删除的记录应立即从 dataGridView 中删除。
////请注意 DATABIND 给出错误,即缺少使用或程序集引用。
代码背后:
private void btnDelete_Click(object sender, EventArgs e)
{
if (txtIDD.Text == "")
{
MessageBox.Show("Please fill ID no. of record to Delete", "Important Message");
}
else
{
try
{
OleDbCommand Cmd = new OleDbCommand();
Cmd.Connection = conn;
conn.Open();
Cmd.CommandText = "DELETE FROM AddressBook WHERE ID="+txtIDD.Text;
Cmd.CommandType = CommandType.Text;
Cmd.ExecuteNonQuery();
Cmd.Connection.Close();
conn.Close();
dataGridView3.Update();
MessageBox.Show("Delete Succesfull");
}
catch (System.Exception err)
{
dataGridView3.DataSource = dt;
dataGridView3.DataBind();
dataGridView3.Update();
this.label27.Visible = true;
this.label27.Text = err.Message.ToString();
}
}
}
【问题讨论】:
-
此代码易受 SQL 注入攻击
-
只是我个人的意见,但是如果网格包含应该删除的数据,我会颠倒逻辑:用户输入文本,您在网格中搜索相关记录,执行在数据库中删除,然后直接从网格中删除记录或从底层绑定数据源中删除记录。 (额外的好处是您还可以直接对选定的行执行删除操作)