Reputation: 13824
Hi I am working i C# window form and mySQL database, I was able to connect to the database, retrieve data and display it in DataGridView.
Now if user click to a row in the DataGridView and press Delete button, I want that selected row to be deleted in database.
Problem is I need to know which column(s) is primary key(s) in order to delete it from database by using this SQL query:
DELETE FROM (selected table) WHERE (Primary column's name(s) = value(s) of primary key column(s) of selected row)
the Bold part is where I am stuck at, can some body help me out or know how other way to delete the selected row in database?
Upvotes: 0
Views: 5666
Reputation: 620
You can use sql query to get primary keys from a table SHOW KEYS FROM table WHERE Key_name = 'PRIMARY'
Upvotes: 4
Reputation: 16584
If you do not know ahead of time what the primary key column is, then you need to examine the table's information to find it. The answers in this question should give you a clue on how to proceed with MySQL, using the SHOW INDEX
MySQL call which is documented here.
Upvotes: 2
Reputation: 1166
You can assign the value of the Primary Key in the datagridview in another column (hidden) so that when the Delete() function is called, you can get the value of the primary key:
Int64 iRecordId =0;
int selectedIndex = 0;
if (datagridview1.SelectedRows.Count > 0)
{
selectedIndex = datagridview1.SelectedRows[0].Index;
iRecordId = Convert.toInt64(datagridview1.Rows[selectedIndex].Cells[0].Value.toString());
// insert delete commands heere
}
Assuming the first column is the primary key.
Upvotes: 1