这是我运行程序时的datagridview(照片):
以下是程序中GUI的照片:
我希望当用户选择“ID 9”并单击“删除”按钮时,它会删除所选行并在数据库中删除它。
我怎么能这样做?我的意思是,我应该把命令放在什么地方?我知道我的命令缺少“WHERE”子句,但我不知道在“WHERE”子句中放入什么。
以下是我现在正在执行的代码(以下代码只需单击即可删除所有行)
deleteButton.Click += new System.EventHandler(this.DeleteRecord);
private DeleteRecord(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "DELETE FROM [Record]";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
{
DataTable ds = new DataTable();
adapter.Update(ds);
dataGridView.DataSource = ds;
cmd.ExecuteNonQuery();
}
}
}
}
现在,我的问题是,当用户选择单行时,如何从datagridview中删除它并将其更新到数据库?请帮忙。感谢。
编辑我已经尝试过此代码:
deleteButton.Click += new System.EventHandler(this.DeleteRecord);
private void DeleteRecord(object sender, EventArgs e)
{
int i = dataGridView.SelectedCells[0].RowIndex;
string strID = dataGridView.Rows[i].Cells[0].Value.ToString();
if (fifthForm.comboBox1.Text == "English")
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "DELETE FROM [Record] WHERE [ID] = @ID";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("ID", System.Data.OleDb.OleDbType.Integer);
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
{
DataTable ds = new DataTable();
cmd.Parameters["ID"].Value = strID;
adapter.Update(ds);
dataGridView.DataSource = ds;
cmd.ExecuteNonQuery();
}
}
conn.Close();
}
}
}
但为什么当我点击“删除”按钮时,它会删除datagridview中的所有记录,但它不会更新到数据库?而且我还希望只选择要删除的选定行。
由于
答案 0 :(得分:1)
你可以像这个示例代码那样做:
string query = "DELETE FROM [Record] WHERE ID = 9";
或者来自某些控件,例如:
string query = "DELETE FROM [Record] WHERE ID =" + idTextBox.Text;
SelectedRow的更新:
deleteButton.Click += new System.EventHandler(this.DeleteRecord);
private DeleteRecord(object sender, EventArgs e)
{
foreach(DataGridViewRow row in DataGridView1.SelectedRows)
{
int rowIdToDelete = row.Cells[ID].Value;
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "DELETE FROM [Record] WHERE ID = " + rowIdToDelete;
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
{
DataTable ds = new DataTable();
adapter.Update(ds);
dataGridView.DataSource = ds;
cmd.ExecuteNonQuery();
}
}
}
}
}
答案 1 :(得分:0)
您需要在删除语句中添加where
条件。
这样的事情: -
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "DELETE FROM [Record] WHERE ID =" + idTextBox.Text;
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
{
DataTable ds = new DataTable();
adapter.Update(ds);
dataGridView.DataSource = ds;
cmd.ExecuteNonQuery();
}
}
}