通过contextmenustrip删除datagridview和数据库中的数据

时间:2018-06-23 14:56:08

标签: c# datagridview

我可以寻求帮助吗? 我在我的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);

    }

1 个答案:

答案 0 :(得分:0)

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

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