Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListView AutoResizeColumns based on both Column content and header

we use this two methods to adjust column length based on Column content and header resp.

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

But how to adjust based on both? i.e. adjust to the longest length for header and column content.

like image 323
william007 Avatar asked Jan 03 '13 04:01

william007


3 Answers

lvw.Columns[0].Width = -2

See remarks in MSDN for details: http://msdn.microsoft.com/en-us/library/system.windows.forms.columnheader.width.aspx

Also note that MSDN says that 'To autosize to the width of the column heading, set the Width property to -2.', but actually it works for column heading AND column contents.

Here is a code to prove that:

    lvw.Columns.Add(new String('x', 25));   // short header
    lvw.Items.Add(new String('x', 100));    // long content

    lvw.Columns[0].Width = -2;
    // in result column width will be set to fit content
like image 84
Anton Kedrov Avatar answered Nov 07 '22 21:11

Anton Kedrov


As answered here, calling both resizing options do the job :

myListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
myListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
like image 23
Tanguy Avatar answered Nov 07 '22 20:11

Tanguy


This is what I use to adjust column width to both content and header:

public static void autoResizeColumns(ListView lv)
{
    lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
    ListView.ColumnHeaderCollection cc = lv.Columns;
    for (int i = 0; i < cc.Count; i++)
    {
        int colWidth = TextRenderer.MeasureText(cc[i].Text, lv.Font).Width + 10;
        if (colWidth > cc[i].Width)
        {
            cc[i].Width = colWidth;
        }
    }
}

Example use:

autoResizeColumns(listView1);

The method isn't that well tested, but at least it works in the context I'm using it in.

like image 9
matsolof Avatar answered Nov 07 '22 22:11

matsolof