从 DGV 和 SQLite 数据库中删除条目 (C#)
Delete Entry from DGV and SQLite DB (C#)
在我的程序中,我在一个表格上有一个 dgv。当我从 dgv 中删除一个条目时,我还想从 SQLite 数据库中删除该条目,这样它就不会重新出现。
我有一个 'id' 列(PRIMARY KEY AUTOINCREMENT),因此每个项目都是唯一的。
我在访问已删除行的 'id' 时遇到了问题。
下面是部分代码:
DialogResult deleteitem = MessageBox.Show("Delete the selected item?", "Delete Item", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
if (deleteitem == DialogResult.Yes)
{
if (!this.dataGridView1.Rows[this.rowIndex].IsNewRow)
{
SetConnection();
sqlconnection.Open();
this.dataGridView1.Rows.RemoveAt(this.rowIndex);
sqlcmd = new SQLiteCommand("DELETE FROM table1 WHERE id=???", sqlconnection);
sqlcmd.ExecuteNonQuery();
}
}
首先 - 在从网格中删除行之前,您需要构建 SQLLiteCommand。您可以使用上面评论中建议的任何一种方法。您可以像这样访问 DataBoundItem:
MyRowDataType dataRow = (MyRowDataType)this.dataGridView1.Rows[this.rowIndex].DataBoundItem;
然后你可以这样删除(但你需要知道你的基础数据的类型并将MyRowDataType更改为你的数据类型):
sqlcmd = new SQLiteCommand("DELETE FROM table1 WHERE id=" + dataRow.ID, sqlconnection);
或者您可以将 ID 列作为隐藏列添加到您的 DataGridView 并以这种方式访问该值:
sqlcmd = new SQLiteCommand("DELETE FROM table1 WHERE id=" + this.dataGridView.Rows[this.rowIndex].Cells["IDColumnName"].Value, sqlconnection);
在我的程序中,我在一个表格上有一个 dgv。当我从 dgv 中删除一个条目时,我还想从 SQLite 数据库中删除该条目,这样它就不会重新出现。
我有一个 'id' 列(PRIMARY KEY AUTOINCREMENT),因此每个项目都是唯一的。
我在访问已删除行的 'id' 时遇到了问题。
下面是部分代码:
DialogResult deleteitem = MessageBox.Show("Delete the selected item?", "Delete Item", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
if (deleteitem == DialogResult.Yes)
{
if (!this.dataGridView1.Rows[this.rowIndex].IsNewRow)
{
SetConnection();
sqlconnection.Open();
this.dataGridView1.Rows.RemoveAt(this.rowIndex);
sqlcmd = new SQLiteCommand("DELETE FROM table1 WHERE id=???", sqlconnection);
sqlcmd.ExecuteNonQuery();
}
}
首先 - 在从网格中删除行之前,您需要构建 SQLLiteCommand。您可以使用上面评论中建议的任何一种方法。您可以像这样访问 DataBoundItem:
MyRowDataType dataRow = (MyRowDataType)this.dataGridView1.Rows[this.rowIndex].DataBoundItem;
然后你可以这样删除(但你需要知道你的基础数据的类型并将MyRowDataType更改为你的数据类型):
sqlcmd = new SQLiteCommand("DELETE FROM table1 WHERE id=" + dataRow.ID, sqlconnection);
或者您可以将 ID 列作为隐藏列添加到您的 DataGridView 并以这种方式访问该值:
sqlcmd = new SQLiteCommand("DELETE FROM table1 WHERE id=" + this.dataGridView.Rows[this.rowIndex].Cells["IDColumnName"].Value, sqlconnection);