удалить данные в datagridview и базе данных через contextmenustrip - PullRequest
0 голосов
/ 23 июня 2018

Могу ли я попросить помощи?Я использую contextmenustrip в моем datagridview, и у него есть кнопка удаления.Я хочу удалить данные в 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 голосов
/ 23 июня 2018

Приведенный ниже код поможет вам достичь результата, указанного в вашем вопросе.

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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...