C# 通过contextmenustrip删除datagridview和数据库中的数据
我可以请你帮忙吗? 我在datagridview中使用contextmenustrip,它有一个删除按钮。我想删除datagridview和数据库中的数据。我该怎么做?我正在使用VisualStudio2010 谢谢:)C# 通过contextmenustrip删除datagridview和数据库中的数据,c#,datagridview,C#,Datagridview,我可以请你帮忙吗? 我在datagridview中使用contextmenustrip,它有一个删除按钮。我想删除datagridview和数据库中的数据。我该怎么做?我正在使用VisualStudio2010 谢谢:) 下面的代码将帮助您实现问题中所示的结果 private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("Yo
下面的代码将帮助您实现问题中所示的结果
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Your connection string");
conn.Open();
//Thinking that the first cell in every row contains the primary key, it will get the primary key from the first selected row
string key = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
SqlCommand cmd = new SqlCommand("delete from YourTableName where id = " + key, conn);
cmd.ExecuteNonQuery();
//Get the index of the selected row and delete it from the rows
int indexOfSelectedRow = dataGridView1.SelectedRows[0].Index;
dataGridView1.Rows.RemoveAt(indexOfSelectedRow);
}
使用数据表。使数据表成为DGV的数据源。DGV和DataTable的行和列索引相同。因此,当从DGV中删除一行时,请从datatable中删除同一行。您可以使用数据库中的适配器填充数据表。然后从datatable中删除数据后,可以使用datatable accept updates方法,该方法将自动更改数据库中的值?这是连接多个表的结果吗?还是来自单个数据库表的数据?还是数据库中的视图?需要知道数据在您的DataGridView@Robertcode数据来自单个数据库表。我收到一个错误。它说“您的SQL语法有错误;请检查与您的MySQL服务器版本对应的手册,以便在第1行的“*from customerTable where custNo=0000013”附近使用正确的语法”很抱歉,我是新来的这篇文章您的代码与数据库连接和操作有关,可能存在一些问题。
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Your connection string");
conn.Open();
//Thinking that the first cell in every row contains the primary key, it will get the primary key from the first selected row
string key = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
SqlCommand cmd = new SqlCommand("delete from YourTableName where id = " + key, conn);
cmd.ExecuteNonQuery();
//Get the index of the selected row and delete it from the rows
int indexOfSelectedRow = dataGridView1.SelectedRows[0].Index;
dataGridView1.Rows.RemoveAt(indexOfSelectedRow);
}