Zed McJack
Zed McJack

Reputation: 61

Adjust the column width only when its content cant fit in

I have form with DataGridView on it that displays data. Everything looks fine except when one of the columns content is wider then the column width. So I searched and found a line of code that I added to my Adjust_the DGV_width method so that columns width is adjusted

foreach (DataGridViewColumn col in zGrid1.Columns)
{
    col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}

It works nicely but it is ugly and I would prefer to keep the columns width as is except when there is content that cant fit in. How can I programmaticaly find out what is the width of the content that cant fit columns width? Here is how it looks now, but I prefer when there is more space in columns.

The form

Upvotes: 0

Views: 33

Answers (1)

EpicKip
EpicKip

Reputation: 4033

This can be easily achieved by checking the column width after setting it to autosize.

Example:

int myDefaultWidth = 100;
myDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
foreach ( DataGridViewColumn column in myDataGridView.Columns )
{
    if ( column.Width < myDefaultWidth)
    {
        column.Width = myDefaultWidth;
    }
}

Upvotes: 1

Related Questions