简体   繁体   中英

C# Datagridview set column width to prefered size when datagrid is on fill

I have a datagridview, that is set to "Fill" because that way you have no ugly blank spots. Now I want to resize 2 columns so the content is fully shown.

With this piece of code I can change the width of one column:

DataGrid.Columns[1].Width = DataGrid.Columns[1].GetPreferredWidth(DataGridViewAutoSizeColumnMode.AllCells, true); 

But when I add it for the other cell that needs to be resized

DataGrid.Columns[5].Width = DataGrid.Columns[5].GetPreferredWidth(DataGridViewAutoSizeColumnMode.AllCells, true);

It overrides the first one, so only the last cell will be resized correctly.

Does anyone have an idea on how to fix this?

Perform this in the parent's (Form's) Load event and not the constructor.

Even if the column's auto size mode is set to Fill, the columns' resulting values won't be set until it loads.

Let me know if I should elaborate. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM