【发布时间】:2018-06-23 14:56:08
【问题描述】:
我可以请求帮助吗? 我在我的 datagridview 中使用 contextmenustrip,它上面有一个删除按钮。我想删除 datagridview 和数据库中的数据。我怎样才能做到这一点?我正在使用 Visual Studio 2010
谢谢你:)
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
string myConnection = "datasource=localhost;port=3306;username=root;password=root;";
MySqlConnection conn = new MySqlConnection(myConnection);
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 = dgvCustomer.SelectedRows[0].Cells[0].Value.ToString();
MySqlCommand cmd = new MySqlCommand("Delete * from customerTable WHERE custNo = '" + key + "'", conn);
cmd.ExecuteNonQuery();
//Get the index of the selected row and delete it from the rows
int indexOfSelectedRow = dgvCustomer.SelectedRows[0].Index;
dgvCustomer.Rows.RemoveAt(indexOfSelectedRow);
}
【问题讨论】:
-
使用数据表。将 DataTable 设为 DGV 的数据源。 DGV和DataTable的行和列索引是一样的。因此,当从 DGV 中删除一行时,请从数据表中删除同一行。您可以使用数据库中的适配器填充 DataTable。然后从数据表中删除数据后,您可以使用数据表接受更新方法,该方法将自动更改数据库中的值。
-
DataGridView 中有什么?是连接多个表的结果吗?还是来自单个数据库表的数据?或者它是数据库中的视图?需要知道数据在 DataGridView 中代表什么
-
@Robertcode 数据来自单个数据库表。
标签: c# datagridview