如何删除keyBoard上的DataGridView行删除按钮单击?

时间:2014-03-21 08:07:42

标签: c# .net wpf winforms

Hei到目前为止我做了什么..现在使用contextmenu我可以删除我的网格行

 private void dataGridViewEmploymentAttribute_MouseDown(object sender, MouseEventArgs e)
    {
        if (_IsLocked != true)
        {
            dataGridViewEmploymentAttribute.ContextMenuStrip = AttributecontextMenuForDelete;


            if (e.Button == MouseButtons.Right)
            {
                DataGridView current = (DataGridView)sender;
                var hti = dataGridViewEmploymentAttribute.HitTest(e.X, e.Y);
                dataGridViewEmploymentAttribute.ClearSelection();
                dataGridViewEmploymentAttribute.Rows[hti.RowIndex].Selected = true;

            }

        }
    }

    private void AttributecontextMenuForDelete_Click(object sender, EventArgs e)
    {
        if (_IsLocked != true)
        {
            Int32 rowToDelete = dataGridViewEmploymentAttribute.Rows.GetFirstRow(DataGridViewElementStates.Selected);
            var AttributeTypeId = dataGridViewEmploymentAttribute.Rows[rowToDelete].Cells["ccAttributeId"].Value.ToString();

            PersonController obj = new PersonController();
            List<EmploymentAttribute> _type = new List<EmploymentAttribute>();
            //var id=_type.Where(q=>q.Name==).Select(p=>p.TypeId)
            DialogResult dialogResult = MessageBox.Show("Are you sure you want to mark this attribute as deleted", " ", MessageBoxButtons.YesNo);
            if (dialogResult == DialogResult.Yes)
            {
                obj.DeleteAttributeById(Convert.ToInt32(AttributeTypeId));
                dataGridViewEmploymentAttribute.Rows.RemoveAt(rowToDelete);
                dataGridViewEmploymentAttribute.ClearSelection();
                MessageBox.Show("Attribute deleted successfully");
            }
            else if (dialogResult == DialogResult.No)
            {
                //do something else
            }
        }
    }

但问题是客户的要求是这样的,在选择任何一行时..如果你点击键盘的删除按钮,它就会删除该行..

3 个答案:

答案 0 :(得分:1)

我更喜欢使用ProcessCmdKey覆盖

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        // Delete Key - Delete Selected Row!
        if (keyData == Keys.Delete)
        {
            DeleteSelectedRow();
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    } 

答案 1 :(得分:0)

编写 KeyDown 事件脚本的问题在哪里?

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete) Console.Beep();
    }

如果您确实处于编辑模式,则可以使用 PreviewKeyDown 事件:

private void dgv_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyCode == Keys.Delete) Console.Beep();
}

当然这可能让用户感到惊讶..!

您还必须为表单启用 KeyPreview 。如果这是一个问题,您可以在GridView的输入保留事件中启用和停用KeyPreview。

答案 2 :(得分:0)

private void dgv1_KeyDown(Object sender,KeyEventArgs e)
{
    if(e.key==Key.Delete)
 {
               //check here whether row is selected or not and remove that one
        }
}

这对你有帮助......