Winforms DataGridView自定义编辑控件/单元格 [英] Winforms DataGridView custom edit control/cell

查看:239
本文介绍了Winforms DataGridView自定义编辑控件/单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Winforms应用程序中为DataGridView创建一个自定义编辑控件,并且我想在用户按下Enter键但在datagridview滚动到下一行之前引发一个事件。我不太在乎事件是由单元格引发的,还是由编辑控件引发,因为我可以根据需要传播事件。到目前为止,我已经尝试覆盖我继承自的DataGridViewTextBoxCell类的OnKeyDown和OnKeyUp方法,并且如果单元格处于编辑模式,则似乎都不会调用这些方法。我还尝试在编辑控件中处理TextBox控件的KeyDown事件。确实会调用此函数,但是只有在DataGridView滚动到下一行之后才会发生(我需要在滚动之前引发事件)。有任何想法吗?预先感谢您的帮助。

I'm creating a custom editing control for my DataGridView in my winforms application, and I'd like to raise an event when the user hits the enter key, but before the datagridview scrolls to the next row. I don't really care if the event is raised by the cell, or the editing control as I can propagate the event as needed. So far I've tried to override both the OnKeyDown and OnKeyUp methods of the DataGridViewTextBoxCell class which I'm inheriting from and neither of these methods seems to be called if the cell is in editing mode. I also tried Handling the KeyDown event of the TextBox control in my editing control. This one does get called, but it happens only after the DataGridView has already scrolled to the next row (I need to raise the event before the scroll). Any ideas? Thanks in advance for the help.

推荐答案

如果要创建自定义的 DataGridView 控件,则可以覆盖 DataGridView 类中的 ProcessCmdKey 事件。

if you are creating a custom DataGridView control then you can override ProcessCmdKey event in DataGridView class.

protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
    int ColumnIndex = dataGridView1.CurrentCell.ColumnIndex;
    int RowIndex = dataGridView1.CurrentCell.RowIndex;
    if (keyData == Keys.Return || keyData == Keys.Enter)
    {                                
        if (ColumnIndex == dataGridView1.Columns.Count - 1)
        {
            dataGridView1.Rows.Add();
            dataGridView1.CurrentCell = dataGridView1.Rows[RowIndex].Cells[0];
        }
        else
            dataGridView1.CurrentCell = dataGridView1.Rows[RowIndex].Cells[RowIndex];

        return true;
    }
    else
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

这篇关于Winforms DataGridView自定义编辑控件/单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆