How can I delete a dataGridView line on a keyboard delete key? WITH#

How to delete the selected row by pressing the delete key on the keyboard (delete from the DataGridView and delete from the database)?

here, as I populate the dataGridView:

private void GetDate() { SqlDataAdapter adapter = new SqlDataAdapter("SELECT id as [ID],description as [Description],unit as [Unit], qty as [Quantity],unitRate as [Unit Rate], amount as [Amount], _datetime as [Date] FROM tbl_BOQ WHERE projectId = "+id, conn); adapter.SelectCommand.CommandType = CommandType.Text; DataTable table = new DataTable(); table.Clear(); adapter.Fill(table); dataGridView1.DataSource = table; } 
+4
source share
2 answers

I am using the DataGridView KeyDown event, and the handler determines whether the Delete key has been pressed:

if e.KeyCode == Keys.Delete...

Then find which element / row to remove by getting the SelectedRows property if your DataGridView is in FullRowSelect or RowHeaderSelect mode, otherwise you can define a row with something like this:

i = SelectedCells[0].RowIndex

then

DataGridView.Rows[i].DataBoundItem

You just need to remove the corresponding record from the database and possibly update the DataGridView based on its binding ...

+6
source

Have you tried to use the KeyPress event DataGridView ?

Then you can use the SelectedRows property of your DataGridView.

0
source

Source: https://habr.com/ru/post/1368939/


All Articles