Automatically resize ListView columns to fit their data in C#

ListView columns

It’s actually pretty easy to automatically resize ListView columns to fit their data. If you set a ListView column’s width to -1, it automatically resizes to fit the data it contains. If you set the width to -2, it resizes to fit its data and its column header.

This example displays buttons that let you set the ListView‘s column widths to 100 pixels, -1, or -2. The program uses the following SetListViewColumnSizes method to set all of the column widths at once.

// Set the listView's column sizes to the same value.
private void SetListViewColumnSizes(ListView lvw, int width)
{
    foreach (ColumnHeader col in lvw.Columns)
        col.Width = width;
}

This code simply loops through the ListView control’s columns and sets their values to whatever value was passed into the method.


Download Example   Follow me on Twitter   RSS feed




This entry was posted in controls and tagged , , , , , , , , . Bookmark the permalink.

3 Responses to Automatically resize ListView columns to fit their data in C#

  1. inam says:

    This was nice trick or hack and it just solved the issue. Thanks a lot.

  2. Mwangi says:

    Kindly help how i can ad a delete and insert commamd in one butto to insert then delet

    • RodStephens says:

      Sorry but I don’t understand your question. Do you want a single button to insert something and then delete something else? Are you inserting and deleting items in a string? ListView? Database? Something else?

      In general, the button’s code can simply execute one command and then another. Let me know what you have in mind and I’ll try to help more.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.