C# ListView Column Width Auto

后端 未结 10 1004
傲寒
傲寒 2020-11-28 07:04

How can I set the column width of a c# winforms listview control to auto. Something like width = -1 / -2 ?

相关标签:
10条回答
  • 2020-11-28 08:02

    It is also worth noting that ListView may not display as expected without first changing the property:

    myListView.View = View.Details; // or View.List
    

    For me Visual Studio seems to default it to View.LargeIcon for some reason so nothing appears until it is changed.

    Complete code to show a single column in a ListView and allow space for a vertical scroll bar.

    lisSerials.Items.Clear();
    lisSerials.View = View.Details;
    lisSerials.FullRowSelect = true;
    
    // add column if not already present
    if(lisSerials.Columns.Count==0)
    {
        int vw = SystemInformation.VerticalScrollBarWidth;
        lisSerials.Columns.Add("Serial Numbers", lisSerials.Width-vw-5);
    }
    
    foreach (string s in stringArray)
    {
        ListViewItem lvi = new ListViewItem(new string[] { s });
        lisSerials.Items.Add(lvi);
    }
    
    0 讨论(0)
  • 2020-11-28 08:03

    This solution will first resize the columns based on column data, if the resized width is smaller than header size, it will resize columns to at least fit the header. This is a pretty ugly solution, but it works.

    lstContacts.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
    colFirstName.Width = (colFirstName.Width < 60 ? 60 : colFirstName.Width);
    colLastName.Width = (colLastName.Width < 61 ? 61 : colLastName.Width);
    colPhoneNumber.Width = (colPhoneNumber.Width < 81 ? 81 : colPhoneNumber.Width);
    colEmail.Width = (colEmail.Width < 40 ? 40 : colEmail.Width);
    

    lstContacts is the ListView. colFirstName is a column, where 60 is the width required to fit the title. Etc.

    0 讨论(0)
  • 2020-11-28 08:04

    Use this:

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

    from here

    0 讨论(0)
  • 2020-11-28 08:04

    I made a program that cleared and refilled my listview multiple times. For some reason whenever I added columns with width = -2 I encountered a problem with the first column being way too long. What I did to fix this was create this method.

    private void ResizeListViewColumns(ListView lv)
    {
        foreach(ColumnHeader column in lv.Columns)
        {
            column.Width = -2;
        }
    }
    

    The great thing about this method is that you can pretty much put this anywhere to resize all your columns. Just pass in your ListView.

    0 讨论(0)
提交回复
热议问题