如何删除键盘上的dataGridView行删除键按? C#

时间:2011-08-25 11:13:58

标签: c# .net winforms datagridview

如何删除键盘上的选定行删除键按下(从dataGridView中删除并从数据库中删除)?

这里我如何填充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;


        }

2 个答案:

答案 0 :(得分:7)

我使用DataGridView的KeyDown事件,并在处理程序中确定它是否是按下的Delete键:

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

如果DataGridView在FullRowSelect或RowHeaderSelect模式下,则通过获取SelectedRows属性来查找要删除的项/行,否则您可以使用以下内容确定行:

i = SelectedCells[0].RowIndex

然后:

DataGridView.Rows[i].DataBoundItem

然后你只需要从数据库中删除相应的记录,并可能刷新DataGridView,取决于它如何绑定......

答案 1 :(得分:0)

您是否尝试过使用KeyPressDataGridView事件?

然后您可以使用DataGridView的SelectedRows属性。