Ronaldinho Learn Coding
Ronaldinho Learn Coding

Reputation: 13824

How to delete selected row on datagridview and that also reflects to the database?

I am working with C# Window Form, I have created a form connect to mySQL database and it display list of databases, list of tables on each database and also tables contents of each table.

Questions that I have here:

  1. After I selected a random cell in the table (datagridview) and click Delete button, I want that row (corresponding to the selected cell) to be deleted on the database.

  2. I also need that the datagridview table content also will be refreshed and updated (with that row has been removed). (This part I think I can do if I know how to do the part 1)

So I need help with the question 1, one of those things I can't not figure out is that how can I write the SQL statement to put in the SQLadapter or SQLcommandbuilder or whatever it is. I know the SQL statement should be like:

Delete from (selected Table) Where (THIS IS THE PART WHERE I STUCK AT) => I dont know what to put in this condition, how to get it?

Any helps and advises is really appreciated!

Upvotes: 0

Views: 1665

Answers (1)

Mateus Schneiders
Mateus Schneiders

Reputation: 4903

The delete statement should consider all the selected table primary key columns and the selected row from the datagridview.

How to get the primary key columns:

SELECT `COLUMN_NAME`
 FROM `information_schema`.`COLUMNS`
WHERE (`TABLE_SCHEMA` = 'dbName')
  AND (`TABLE_NAME` = 'tableName')
  AND (`COLUMN_KEY` = 'PRI');

Source: A better way to get Primary Key columns

How your delete statement should look like:

DELETE FROM <TABLE> 
  WHERE <PRIMARY_KEY_COLUMN_1> = <ROW_VALUE_1>
    AND <PRIMARY_KEY_COLUMN_2> = <ROW_VALUE_2>

You see, the table could have multiple columns uniquely identifying a row. There is also the possibility of existing a reference for that very row on another table, which would prevent you from deleting it.

It would look like this:

List<string> primaryKeyColumns = GetPrimaryKeyColumns(SelectedDB, SelectedTable);
string deleteWhereClause = string.Empty;
foreach (string column in primaryKeyColumns)
{
    DataGridViewRow row = datagridview.CurrentCell.OwningRow;
    string value = row.Cells[column].Value.ToString();

    if (string.IsNullOrEmpty(deleteWhereClause))
    {
        deleteWhereClause = string.Concat(column, "=", value);
    }
    else 
    {

        deleteWhereClause += string.Concat(" AND ", column, "=", value);
    }
}
string deleteStatement = string.Format("DELETE FROM {0} WHERE {1}", SelectedTable, deleteWhereClause);

The method GetPrimaryKeyColumns returns the names of all the primary key columns of the selected table using the select statement i posted. You would also have to deal with other types of columns such as dates and strings, but that's basically what you will have.

Upvotes: 1

Related Questions