8

How can we set the width of each column according to the length of its content in a ListView? I hate having to keep changing the size of each column at runtime. Is there an MSDN doc that has this info? I can't find where I should be looking

Thank you

3 Answers3

37

Use both resizing options after populating the list:

myListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
myListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

This will size columns to the width of column data, and then restore minimum width for column headers without completely trashing the original auto-sizing.

Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99
Graham Povey
  • 939
  • 8
  • 8
  • Wow, running both works, great trick! – bkribbs Aug 27 '15 at 18:54
  • Very nice trick. But why does it work? According to MSDN, ColumnHeaderAutoResizeStyle.HeaderSize should shrink column to the header width but this does not happen? Why? Bug in listview that luckily is very useful or bad documentation? – 4LegsDrivenCat Dec 24 '18 at 16:46
7

Review the ColumnHeader.AutoResize() method. Call it after populating the Items, the form's OnLoad() method is the first chance.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • The Timer on S/O is really giving me the s s. I had one minute left to wait, and after that minute, it said 46seconds left, so I waited 46seconds. Then it said 10seconds left. :@ –  Apr 05 '11 at 20:51
  • LOL you're very welcome @Hans. It's not the "wait" that jerks me, it's the fact that the timer lied to me. :) –  Apr 06 '11 at 00:38
0

I got it:

viewer.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
  • 2
    But what if the column is blank? One of the common problems with column auto-resizing is that, although ideally it would size according to the content with a minimum width of the column header, the auto-size properties force an empty column to be about two pixels in width. – Devin Burke Apr 05 '11 at 20:42
  • Yeah, @Justin, I agree with you. I just realised that. What I did was resize according to content, and when I know that the contents of the columns is not likely to be wider than the column headers themselves, I just resize according to the header. But still, that's not the most desirable way of doing it. –  Apr 06 '11 at 00:43
  • 1
    This is the problem I'm having. I want something like "resize by header, then by content ONLY if content is wider than the header". – crdx Jun 11 '12 at 12:11