Search code examples
c#exceldatagridviewbindingediting

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


I have a DataGridView and a textbox. I want show datagridview cell value (in editing mode)to textbox like Excel. I'm trying something like this:

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);
    }

and:

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;            
    }

but not working currently. Please Help Me. thanks.

SOLVE: Change "KeyPress" To keyUp To work corrently.


Solution

  • I believe this is an answer to your question: Change datagridview cell value in edit mode

    I recoded the idea from the link above to your case and tested it. I created _KeyUp event within the editing control. You should add more stuff, like testing, if the editing control is type of TextBox.

    enter image description here

    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
    

    EDIT:

    Oh and there's also another fine way to achieve that - binding. See this article: A Detailed Data Binding Tutorial If you look at chapter What else can you do with data binding?, you'll see exactly your case.