Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

c# - DataGridView: Change Edit Control size while editing

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, when entering edit mode, a DataGridViewTextBoxEditingControl is placed at the cell position. I tried to change the bounds/size of this control, but result is just a short flicker of my desired size. It gets directly overpainted the original, truncated way.

Any ideas on how to get this working?

Thanks,

Timo

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...