0

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?

Ronaldinho Learn Coding
  • 13,254
  • 24
  • 83
  • 110
  • Check this one http://msdn.microsoft.com/en-us/library/system.data.datatable.primarykey.aspx may be it will help you :) – andy Feb 18 '13 at 04:58
  • @andy I spent few hours and also looked at what you gave me - the Data table with Primary Key Properties but still can't figure out. Help me! – Ronaldinho Learn Coding Feb 18 '13 at 05:04

3 Answers3

4

You can use sql query to get primary keys from a table SHOW KEYS FROM table WHERE Key_name = 'PRIMARY'

Core
  • 601
  • 2
  • 7
  • 19
  • I tried to execute this query in mySQL and it does returns information of primary key column(s), I wonder how it look like (what are return value and return type) of it in C# because it need a variable to store it for later using. – Ronaldinho Learn Coding Feb 18 '13 at 05:20
  • @RonaldinhoState, the query returns the data in table format and you can get primary keys in a table from **Column_name**. – Core Feb 22 '13 at 14:05
2

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.

Community
  • 1
  • 1
Corey
  • 15,524
  • 2
  • 35
  • 68
  • I tried to execute this query: SHOW INDEX FROM tableName WHERE Key_name = 'PRIMARY'; in mySQL and it does returns information of primary key column(s), I wonder how it look like (what are return value and return type) of it in C# because it need a variable to store it for later using. – Ronaldinho Learn Coding Feb 18 '13 at 05:21
  • The results of the call will probably be a block of text, not a recordset. I don't have a MySQL server to hand to test on, sorry. – Corey Feb 18 '13 at 06:04
1

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.

whastupduck
  • 1,156
  • 11
  • 25