//Except where stated all code and programs in this project are the copyright of Jim Blackler, 2008.
//jimblackler@gmail.com
//
//This is free software. Libraries and programs are distributed under the terms of the GNU Lesser
//General Public License. Please see the files COPYING and COPYING.LESSER.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MiscControls
{
///
/// A utility class that automatically adjusts the widths of a ListView's columns to fix text that
/// is shown by the list view.
///
public class ListViewColumns
{
///
/// Sets what the operation is allowed to do to the column widths.
///
public enum SizeMode
{
///
/// The column is able to expand and shrink to fit the content width.
///
ExpandAndShrink,
///
/// The column is only able to shrink if the column is wider than the content.
///
ShrinkOnly,
///
/// The column is only able to expand if the column is narrower than the content.
///
ExpandOnly
};
///
/// Adjust a list view's columns to fit the contained text
///
/// The list view to adjust
/// The acceptable operations to perform on the column widths
static public void AdjustToFit(ListView listView, SizeMode sizeMode)
{
// Only does anything in columns view
if (listView.View != View.Details)
return;
int margin = 10;
Graphics graphics = listView.CreateGraphics();
int[] maxColumnSize = new int[listView.Columns.Count];
// Measure the column widths
foreach (ListViewItem item in listView.Items)
{
int idx = 0;
foreach (ListViewItem.ListViewSubItem subItem in item.SubItems)
{
int width = graphics.MeasureString(subItem.Text, subItem.Font).ToSize().Width + margin;
if (maxColumnSize[idx] < width)
maxColumnSize[idx] = width;
idx++;
}
}
// Fix the column widths
{
int idx = 0;
foreach (int width in maxColumnSize)
{
if ((sizeMode != SizeMode.ExpandOnly || listView.Columns[idx].Width < width)
&& (sizeMode != SizeMode.ShrinkOnly || listView.Columns[idx].Width > width))
listView.Columns[idx].Width = width;
idx++;
}
}
}
}
}