I do not think that you can achieve this because AutoSizeMode is once installed on DisplayedCells, all behavior is controlled by design. But I have this idea. You need to leave your column (I suppose columns [0] for demo purpose). AutoSizeMode fixed in DataGridViewAutoSizeColumnMode.None . You want to set it as DisplayedCells , because you may need to expand the width of the column or collapse it depending on the length of the cell text. So my idea is that every time CellBeginEdit starts, we set AutoSizeMode to DisplayedCells, and when CellEndEdit starts, we save the Width (which is authorized for you) before switching from AutoSizeMode to None , then assign the column width to this saved value. Here is my code:
//First before loading data private void form_Load(object sender, EventArgs e){ dataGridView.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; //Fill your dataGridView here //......... //......... int w = dataGridView.Columns[0].Width; //reset to None dataGridView.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; dataGridView.Columns[0].Width = w; } //Now for CellBeginEdit and CellEndEdit private void dataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) { if(e.ColumnIndex == 0) //because I suppose the interested column here is Columns[0] dataGridView.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; } private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) { if(e.ColumnIndex == 0){ int w = dataGridView.Columns[0].Width; dataGridView.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; dataGridView.Columns[0].Width = w; } }
I tested the code and it seemed to work fine, there is a case that it will not work, because we are not adding code for this case, that is, when the Cell value is changed by the code.
I have to say that your desire is a little strange, I am not too worried about the column width, the user needs to know how to work with it.
source share