【问题标题】:How to Get datagridview Cell Value in editing mod to show in textbox(like excel)如何在编辑模式中获取 datagridview 单元格值以显示在文本框中(如 excel)
【发布时间】:2019-06-05 13:36:09
【问题描述】:

我有一个 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 以正常工作。

【问题讨论】:

  • 将“KeyPress”更改为 keyUp 以正常工作。

标签: c# excel datagridview binding editing


【解决方案1】:

我相信这是您问题的答案: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

编辑:

哦,还有另一种很好的方法来实现这一点 - 绑定。见这篇文章:A Detailed Data Binding Tutorial 如果您查看您还可以使用数据绑定做什么?一章,您会看到完全符合您的情况。

【讨论】:

  • 此链接目前对我不起作用。你能把你的代码添加到帖子中吗?
  • 我修改了答案。该链接对我来说很好,我不确定问题出在哪里......
  • 谢谢。但是一个字符不存在!.例如datagridviewcell是123,文本框是12。请帮助。
  • 哦,我明白了,对不起。只需尝试将 KeyDown 替换为 KeyUp 事件,这将在 键被击中后获取文本。
  • 谢谢。效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多