4

How can I delete a selected row on keyboard delete key press ( remove from dataGridView and delete from the database ) ?

here how 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;


        }
3
  • Hi, show some code, how is your grid getting populated? how is your page/form looking like? ASP.NET or Windows Forms? Aug 25, 2011 at 11:16
  • it is windows form application not ASP.NET
    – Amer
    Aug 25, 2011 at 11:17
  • hei ..how u did this one..plz help me
    – minakshi
    Mar 21, 2014 at 8:10

2 Answers 2

8

I use the DataGridView's KeyDown event, and in the handler determine if it was the Delete key that was pressed:

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

Then find which item/row to delete by getting the SelectedRows property if your DataGridView is on FullRowSelect or RowHeaderSelect mode, else you can determine the row with something like this:

i = SelectedCells[0].RowIndex

then:

DataGridView.Rows[i].DataBoundItem

You would then simply need to delete the corresponding record from the database, and possibly refresh the DataGridView depening on how its tied in...

2
  • keydown event is not firing for me
    – minakshi
    Mar 21, 2014 at 8:09
  • I used KeyUp because KeyDown is not firing. Nov 17, 2016 at 5:15
2

Have you tried using the KeyPress event of the DataGridView?

Then you could use the SelectedRows property of your DataGridView.

4
  • I think CurrentRow would be appropriate
    – V4Vendetta
    Aug 25, 2011 at 11:53
  • 1
    That would depend upon your setting for MultiSelect. msdn.microsoft.com/en-us/library/…
    – Paul
    Aug 25, 2011 at 12:04
  • Its a different collection all together
    – V4Vendetta
    Aug 25, 2011 at 12:09
  • Well, the question is how to delete the SELECTED row. If it is multiselect sooner or later, iterating over the SelectedRows rows would be the right decision, I think. Aug 25, 2011 at 23:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.