如何在编辑 mod 时获取 datagridview 单元格值以显示在文本框中(如 excel)

How to Get datagridview Cell Value in editing mod to show in textbox(like excel)

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

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 以正常工作。

我相信这是对您问题的回答:

我将上面 link 中的想法重新编码到您的案例中并进行了测试。我在编辑控件中创建了 _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

编辑:

哦,还有另一种实现该目的的好方法 - 绑定。参见这篇文章:A Detailed Data Binding Tutorial 如果您查看第 您还可以使用数据绑定做什么? 一章,您将完全了解您的情况。