Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# datagridview column autosizemode

I wish that by default the columns uses the

AutoSizeMode = DisplayedCells;

but I wish also the possibility to resize the columns, but DisplayedCells type doesn't allow to resize..

any ideas?

like image 445
ghiboz Avatar asked Feb 17 '23 07:02

ghiboz


2 Answers

You can call the sub DataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells) whenever it's convenient, such as after you've loaded the data. Leave the DataGridView.AutoSizeColumnsMode property alone and the user will still be able to resize the columns themselves, but they'll have a comfortable start. Best of both worlds.

like image 128
John Avatar answered Feb 18 '23 19:02

John


I don't think you can achieve that because the AutoSizeMode once is set to DisplayedCells all the behavior is controlled by design. But I have this idea. You should have to keep your column (I suppose Columns[0] for demonstrative purpose) AutoSizeMode fixed at DataGridViewAutoSizeColumnMode.None. You want to set it as DisplayedCells because you may want the column width to expand or collapse depending on the Cell text length. So my idea is every time the CellBeginEdit starts, we set the AutoSizeMode to DisplayedCells and when the CellEndEdit starts we save the Width (which is autosized for you) before reseting the AutoSizeMode to None, then assign the column Width to that 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 seems to work OK, there is a case that it won't work because we don't add code for that case, that is when the Cell value is changed by code.

I have to say that your want is a little strange, I don't care too much about the column's width, user should know how to do with it.

like image 27
King King Avatar answered Feb 18 '23 21:02

King King