【问题标题】:delete data in datagridview and database through contextmenustrip通过contextmenustrip删除datagridview和数据库中的数据
【发布时间】: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


【解决方案1】:

以下代码将帮助您实现问题中指示的结果。

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);
}

【讨论】:

  • 我遇到了一个错误。它说“您的 SQL 语法有错误;请检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 '* from customerTable where custNo = 0000013' 附近使用正确的语法”
  • 对不起,我是新手
  • 贴出你的数据库连接和操作相关的代码,可能有问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-30
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多