RikSaunderson
RikSaunderson

Reputation: 3765

C# listview optimum column width

I have a C# ListView and I'd like to autosize the column widths based on the contents of the column.

I know that setting the column width to -1 will size the column at the length of the widest member. I know that setting the column width to -2 will size the column at the length of the column header. How do I size the column to be the greater of the two?

I could do something like this:

for (int i = 0; i < listView.Columns.Count; ++i)
{
    listView.Columns[i].Width = -1;
    int width1 = listView.Columns[i].Width;
    listView.Columns[i].Width = -2;
    if (width1 > listView.Columns[i].Width)
        listView.Columns[i].Width = -1;
}

but it does seem fabulously inefficient.

Does anyone have an answer?

Upvotes: 3

Views: 3342

Answers (1)

Josh
Josh

Reputation: 760

You should try

ListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

even though it says "ColumnHeaderAutoResizeStyle.HeaderSize" it should auto resize to the largest item in the column, whether it's the header or a column member

Upvotes: 5

Related Questions