Edit a TextBox cell in DataGridView as if it were a normal TextBox (no jumping on pressing arrows)

后端 未结 1 842
被撕碎了的回忆
被撕碎了的回忆 2021-01-26 05:24

I have \"multiline\" (wordwrapping) textbox columns in a DataGridView. It would be great to be able to edit them as normal TextBoxes, that is, when I press down arrow, I

1条回答
  •  伪装坚强ぢ
    2021-01-26 06:13

    This question here showed me a way to solve it. Here is the code:

    class MyDataGridView : DataGridView
    {
    
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if ((keyData == Keys.Enter) && (this.EditingControl != null))
            {
                //new behaviour for Enter
                TextBox tb = (TextBox)EditingControl;
                int pos = tb.SelectionStart;
                tb.Text = tb.Text.Remove(pos, tb.SelectionLength);
                tb.Text = tb.Text.Insert(pos, Environment.NewLine);
                tb.SelectionStart = pos + Environment.NewLine.Length;
                tb.ScrollToCaret();
                //and do nothing else
                return true;
            }
            else if ((keyData == Keys.Up) && (this.EditingControl != null))
            {
                //programmatically move caret up
                //(look at related question to see how)
                return true;
            }
            else if ((keyData == Keys.Down) && (this.EditingControl != null))
            {
                //programmatically move caret down
                //(look at related question to see how)
                return true;
            }
            //for the rest of the keys, proceed as normal
            return base.ProcessCmdKey(ref msg, keyData);
        }
    }
    

    So this is a simple change of DataGridView and it works. I only had to

    • create this new class, and
    • change two lines from the DesignerClass to use MyDataGridView instead of DataGridView (declaration and initialization)

    and everything else worked as expected.

    Related question: how to programmatically move caret up and down one line.

    0 讨论(0)
提交回复
热议问题