有什么方法可以获得 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/