首页 > 解决方案 > 如何在编辑模式中获取 datagridview 单元格值以显示在文本框中(如 excel)

问题描述

我有一个 DataGridView 和一个文本框。我想向 Excel 等文本框显示 datagridview 单元格值(在编辑模式下)。我正在尝试这样的事情:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        var ctl = e.Control as DataGridViewTextBoxEditingControl;
        if (ctl == null)
        {
            return;
        }
        ctl.KeyPress -= ctl_Keypress;
        ctl.KeyPress += new KeyPressEventHandler(ctl_Keypress);
    }

和:

private void ctl_Keypress(object sender, KeyPressEventArgs e)
    {
        var box = sender as System.Windows.Forms.TextBox;
        if (box == null)
        {                
            return;
        }
        tb_currendCellValue.Text = box.Text;            
    }

但目前不工作。请帮我。谢谢。

解决:将“KeyPress”更改为 keyUp 以正常工作。

标签: c#exceldatagridviewbindingediting

解决方案


我相信这是您问题的答案:Change datagridview cell value in edit mode

我将上面链接中的想法重新编码到您的案例中并对其进行了测试。我在编辑控件中创建了 _KeyUp 事件。如果编辑控件是 TextBox 类型,您应该添加更多内容,例如测试。

在此处输入图像描述

C#

private TextBox CtrlTextbox;
private void DataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (RowIdx >= 0)
    {
        CtrlTextbox = (TextBox)e.Control;
        CtrlTextbox.KeyUp += CopyText;
    }
}

private void CopyText(object sender, KeyEventArgs e)
{
    this.TextBox1.Text = sender.Text;
}

VB.NET

Dim CtrlTextbox As TextBox
Private Sub DataGridView2_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView2.EditingControlShowing
    If RowIdx >= 0 Then
        CtrlTextbox = CType(e.Control, TextBox)
        AddHandler CtrlTextbox.KeyUp, AddressOf CopyText
    End If
End Sub

Private Sub CopyText(sender As Object, e As KeyEventArgs)
    Me.TextBox1.Text = sender.Text
End Sub

编辑:

哦,还有另一种很好的方法来实现这一点 -绑定。请参阅这篇文章:详细的数据绑定教程 如果您查看章节您还可以使用数据绑定做什么?,你会看到你的情况。


推荐阅读