Search code examples
c#winformsdatagridviewtextboxedit

How to edit DataGridView Text cell in a bigger textbox


I have a DataGridView with a TextColumn. Some of the cells can be a bit long to show in a DataGridView, so I truncate the text and add "..." to the text. I don't want to wrap the text to multiple lines.

I would like to let the user edit the text in the column. In the EditingControlShowing I currently set the editing TextBox' text to the full value of the text (otherwise only truncated value shows up). Everything fine so far.

How do I make the editing TextBox expand vertically beyond its cell (the cells are only one line high), to make it easier for the user to edit multi-line entries?


Solution

  • You can change the position and size o editing control. To do so, you need to override PositionEditingControl of a cell and set the position and size of the editing panel and editing control:

    public class MyTextBoxCell : DataGridViewTextBoxCell
    {
        public override void PositionEditingControl(bool setLocation, bool setSize,
            Rectangle cellBounds, Rectangle cellClip, DataGridViewCellStyle cellStyle, 
            bool singleVerticalBorderAdded, bool singleHorizontalBorderAdded, 
            bool isFirstDisplayedColumn, bool isFirstDisplayedRow)
        {
            cellClip.Height = cellClip.Height *4; // ← Or any other suitable height
            cellBounds.Height = cellBounds.Height * 4;
            var r = base.PositionEditingPanel( cellBounds, cellClip, cellStyle, 
                singleVerticalBorderAdded, singleHorizontalBorderAdded, 
                isFirstDisplayedColumn, isFirstDisplayedRow);
            this.DataGridView.EditingControl.Location = r.Location;
            this.DataGridView.EditingControl.Size = r.Size;
        }
        public override void InitializeEditingControl(int rowIndex,
            object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            base.InitializeEditingControl(rowIndex, initialFormattedValue, 
                dataGridViewCellStyle);
            ((TextBox)this.DataGridView.EditingControl).Multiline = true;
            ((TextBox)this.DataGridView.EditingControl).BorderStyle = BorderStyle.Fixed3D;
        }
    }
    

    Then to use it, assign an instance of this cell, to CellTemplate property of the Column which you want to change its editor size:

    this.dataGridView1.Columns[0].CellTemplate = new MyTextBoxCell();
    

    Or you can create a new column and use your custom column:

    public class MyTextBoxColumn:DataGridViewTextBoxColumn
    {
        public MyTextBoxColumn()
        {
            CellTemplate = new MyTextBoxCell();
        }
    }