c# - 将事件附加到 DataGridView 单元格的底层 TextBox

标签 c# winforms .net-2.0

有什么方法可以获得 DataGridView 单元格的底层控制吗? 我想附加正常的 texbox 事件来捕获击键和捕获值的变化。

所以我有 4 列,每一列都包含单元格的数量,一行中的所有单元格都应该根据其类型以不同的方式处理。

基本上我只需要在编辑单元格时触发我的事件。

最佳答案

订阅DataGridView.EditingControlShowing事件,然后订阅你需要的TextBox事件


TextBox.KeyDown 示例:

void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    var txtBox = e.Control as TextBox;
    if (txtBox != null)
    {
        // Remove an existing event-handler, if present, to avoid 
        // adding multiple handlers when the editing control is reused.
        txtBox.KeyDown -= new KeyEventHandler(underlyingTextBox_KeyDown);

        // Add the event handler. 
        txtBox.KeyDown += new KeyEventHandler(underlyingTextBox_KeyDown);
    }
}

void underlyingTextBox_KeyDown(object sender, KeyEventArgs e)
{
    // ...
}

编辑:

现在代码更正确了,因为它遵循了 MSDN 上给出的建议:

The DataGridView control hosts one editing control at a time, and reuses the editing control whenever the cell type does not change between edits. When attaching event-handlers to the editing control, you must therefore take precautions to avoid attaching the same handler multiple times. To avoid this problem, remove the handler from the event before you attach the handler to the event. This will prevent duplication if the handler is already attached to the event, but will have no effect otherwise. For more information, see the example code in the DataGridViewComboBoxEditingControl class overview.

编辑 2:

根据评论:

TextChanged 事件在 EditingControlShowing 之前调用,然后在它之后再次调用。

你可以使用这个技巧来区分这两个调用:

void txtBox_TextChanged(object sender, EventArgs e)
{
    var txtBox = (TextBox)sender;
    if (txtBox.Focused)
    {
        // second call (after EditingControlShowing) the TextBox is focused
    }
    else
    {
        // first call (before EditingControlShowing) the TextBox is not focused
    }
}

关于c# - 将事件附加到 DataGridView 单元格的底层 TextBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5430156/

相关文章:

asp.net - UpdatePanel、Repeater、DataBinding 问题

C# 事件在错误的线程上触发

c# - 用于书签的 Visual Studio 快捷键

c# - 最好在哪里创建对象?

c# - 当所有者绘制模式时如何使列表框项目中的文本居中

c# - 在设计模式下从窗体中删除自定义控件后清除自定义控件属性的 InnerList 元素

c# - 如何以及在何处了解 .net 从 .net 2.0 到 .net 3.5 的变化?

c# - 如何使用 WMI/ADSI 和 C# 在 IIS 中为身份验证的扩展保护启用/禁用/获取状态?

c# - Windows 8 Metro App 仅在读取文件时在调试器中启动

c# - 用文本框中的数字填充字典并将文本框作为键