Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView: How can I make the enter key add a new line instead of changing the current cell?

How can I make the Enter key behave in a Winforms DataGridViewTextBoxCell like it does in a normal Winforms TextBox (add a new line to the text, instead of changing the current cell)?

like image 708
Zach Johnson Avatar asked Jan 08 '10 20:01

Zach Johnson


1 Answers

You can do this by setting the DataGridViewCellStyle.WrapMode property to true. From MSDN:

If WrapMode is False for a cell that contains text, the cell displays the text on a single line, and displays any embedded newline characters as box characters. If WrapMode is True for a cell that contains text, the cell displays newline characters as line breaks, but also wraps any lines that exceed the width of the cell.

You can set this for specific cells by accessing the Style property on a cell, or for all cells in a column by using the DefaultCellStyle for the column.

[Update] To disable the Enter key selectively in your DataGridView, add a Message Filter to the Form containing the DataGridView as shown below:

private KeyMessageFilter m_filter = null;

private void Form1_Load(object sender, EventArgs e)
{
    m_filter = new KeyMessageFilter(this); 
    Application.AddMessageFilter(m_filter);

}

Here is the message filter class:

public class KeyMessageFilter : IMessageFilter
{
    private Form m_target = null;

    public KeyMessageFilter(Form targetForm)
    {
        m_target = targetForm;
    }

    private const int WM_KEYDOWN = 0x0100;

    private const int WM_KEYUP = 0x0101;


    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg == WM_KEYDOWN)
        {
            //Note this ensures Enter is only filtered if in the 
            // DataGridViewTextBoxEditingControl and Shift is not also  pressed.
            if (m_target.ActiveControl != null && 
                m_target.ActiveControl is DataGridViewTextBoxEditingControl && 
                (Keys)m.WParam == Keys.Enter && 
                (Control.ModifierKeys & Keys.Shift) != Keys.Shift)
            {
                return true;
            }

        }

        return false;
    }
}

Now, the Enter key is disabled when editing text and you must press the tab key to move to the next cell. Shift + Enter still adds a newline to the text you are editing.

Hope this helps.

like image 76
Ash Avatar answered Oct 12 '22 06:10

Ash