How can I delete dataGridView row on keyboard delete key press ? c#

18,963

Solution 1

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...

Solution 2

Have you tried using the KeyPress event of the DataGridView?

Then you could use the SelectedRows property of your DataGridView.

Share:
18,963
Amer
Author by

Amer

Updated on June 14, 2022

Comments

  • Amer
    Amer almost 2 years

    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;
    
    
            }
    
    • Davide Piras
      Davide Piras over 12 years
      Hi, show some code, how is your grid getting populated? how is your page/form looking like? ASP.NET or Windows Forms?
    • Amer
      Amer over 12 years
      it is windows form application not ASP.NET
    • minakshi
      minakshi about 10 years
      hei ..how u did this one..plz help me
  • V4Vendetta
    V4Vendetta over 12 years
    I think CurrentRow would be appropriate
  • Paul
    Paul over 12 years
    That would depend upon your setting for MultiSelect. msdn.microsoft.com/en-us/library/…
  • V4Vendetta
    V4Vendetta over 12 years
    Its a different collection all together
  • TheBlastOne
    TheBlastOne over 12 years
    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.
  • minakshi
    minakshi about 10 years
    keydown event is not firing for me
  • Fandi Susanto
    Fandi Susanto over 7 years
    I used KeyUp because KeyDown is not firing.