Adjust ListView columns to fit with WinForms

后端 未结 5 1652
不知归路
不知归路 2021-02-07 21:50

I have face resize problem of listview columns. If you anchor/docking the listview to normal winform than the listview anchor or docking works well. I mean lis

5条回答
  •  -上瘾入骨i
    2021-02-07 22:44

    A simple solution that takes a listview and the index of the column you want to resize automatically, so that the size of the entire listview's client area is utilized to the last pixel, no more and no less, i.e. no ugly horizontal scrollbar appearing even if resizing makes the control smaller.

    You want to call this method from your Resize event handler, and also after adding an element in case a vertical scrollbar appeared after adding more lines than the control has room for vertically.

    I disagree with the idea to react on the ResizeEnd event instead, as mentioned in one of the other posts, since this does not look nice on the screen if Windows is set up to draw windows while moving and resizing. The calculation is quick, so it doesn't create any problems to resize continuously.

    static private void ResizeAutoSizeColumn(ListView listView, int autoSizeColumnIndex)
    {
      // Do some rudimentary (parameter) validation.
      if (listView == null) throw new ArgumentNullException("listView");
      if (listView.View != View.Details || listView.Columns.Count <= 0 || autoSizeColumnIndex < 0) return;
      if (autoSizeColumnIndex >= listView.Columns.Count)
        throw new IndexOutOfRangeException("Parameter autoSizeColumnIndex is outside the range of column indices in the ListView.");
    
      // Sum up the width of all columns except the auto-resizing one.
      int otherColumnsWidth = 0;
      foreach (ColumnHeader header in listView.Columns)
        if (header.Index != autoSizeColumnIndex)
          otherColumnsWidth += header.Width;
    
      // Calculate the (possibly) new width of the auto-resizable column.
      int autoSizeColumnWidth = listView.ClientRectangle.Width - otherColumnsWidth;
    
      // Finally set the new width of the auto-resizing column, if it has changed.
      if (listView.Columns[autoSizeColumnIndex].Width != autoSizeColumnWidth)
        listView.Columns[autoSizeColumnIndex].Width = autoSizeColumnWidth;
    }
    

提交回复
热议问题