0

I'm creating an app and I have a part where I have data in a table (datagridview). In this table I also have a button on each row.

My goal is to click on a button to delete the row where the button was clicked from the table and from the database where the application will fetch the information.

My code is the following:

public void update_tabelas()
{
    string queryprodutos = "SELECT * FROM produtos;";
    DataTable dtprodutos = new DataTable();
    MySqlCommand cmdprod = new MySqlCommand(queryprodutos, mConn);
    MySqlDataAdapter daprod = new MySqlDataAdapter(cmdprod);
    mConn.Open();
    daprod.Fill(dtprodutos);
    mConn.Close();
    this.tabelaprodutos.DataSource = dtprodutos;
    DataGridViewColumn col = new DataGridViewButtonColumn();
    col.Name = "Delete";
    col.DataPropertyName = "Delete";
    col.ReadOnly = true;
    this.tabelaprodutos.Columns.Add(col);
}

This code will fill the table and add the delete button on each row.

Now I don't know how to delete these data from the table and from the database.

I appreciate any suggestions and help.

  • You should delete the row from the database, then reset the grids data source. You could use the grids `CellMouseClick` event to see if the “Delete” button column was clicked, and if so you would know which row to delete. Have you tried anything? – JohnG Jun 13 '17 at 10:03
  • No, I haven't tried anything yet. – MiniKing17 - Tiago Jun 13 '17 at 10:25
  • Well… keep it simple… First set up the `CellMouseClick` event and get it to call a method that displays a simple message box to show which row was clicked. Once you have that working, then add the code to delete that row from the database, then re-set the data source to the grid. Try something, if it doesn’t work post back here. – JohnG Jun 13 '17 at 10:33
  • @JohnG Where do I put the code with this event? In the load form or anywhere else? And I don't exactly how to create this event. – MiniKing17 - Tiago Jun 13 '17 at 13:18
  • See [How to handle click event in Button Column in Datagridview](https://stackoverflow.com/a/13687844/3773066) for setting up the `CellContentClick` event. In that event, call your SQL delete query and update as needed. – OhBeWise Jun 13 '17 at 18:02

1 Answers1

0

From Delete button click event/cell click event get the row index and and remove it from DB and reload datagridview(run the update_tabelas() method)

Znaneswar
  • 3,329
  • 2
  • 16
  • 24