Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;


        }
like image 403
Amer Avatar asked Dec 27 '22 15:12

Amer


1 Answers

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

like image 143
andyhasit Avatar answered Dec 30 '22 11:12

andyhasit