DataGridView: Change Edit Control size while editing

后端 未结 7 897
遇见更好的自我
遇见更好的自我 2020-12-20 16:59

in the DataGridView I want the cell size to expand according to the string length when I edit the cell. Excel does the same.

In the DataGridView, w

7条回答
  •  执笔经年
    2020-12-20 17:06

    You need to start by overriding the DataGridViewCell.PositionEditingPanel Method. You need to redefine your own type of column and your own type of cell to access this method.

    Here is an example on how to do it, that multiply the size of the editing panel (the one that owns the editing control) by 2:

    dataGridView1.AutoGenerateColumns = false; // disable columns auto generation
    
    ... add all columns
    
    // add your special column
    col = new MyColumn();
    col.DataPropertyName = "Text"; // bind with the corresponding property
    dataGridView1.Columns.Add(col); // add the custom column
    
    ... add other columns
    
    public class MyCell : DataGridViewTextBoxCell
    {
        public override Rectangle PositionEditingPanel(Rectangle cellBounds, Rectangle cellClip, DataGridViewCellStyle cellStyle, bool singleVerticalBorderAdded, bool singleHorizontalBorderAdded, bool isFirstDisplayedColumn, bool isFirstDisplayedRow)
        {
            cellBounds.Width *= 2;
            cellClip.Width = cellBounds.Width;
            return base.PositionEditingPanel(cellBounds, cellClip, cellStyle, singleVerticalBorderAdded, singleHorizontalBorderAdded, isFirstDisplayedColumn, isFirstDisplayedRow);
        }
    }
    
    public class MyColumn : DataGridViewTextBoxColumn
    {
        public MyColumn()
        {
            CellTemplate = new MyCell();
        }
    }
    

提交回复
热议问题