Grasshopper
Grasshopper

Reputation: 4977

How To Resize Certain ListView Columns Proportional To Remaining Size Of ListView

I am attempting to re-size only certain columns of a ListView based on the remaining size after any static width column widths are calculated. For example, I do not want columns, such as quantity, price, etc... to resize but, I would like columns that typically have wider data such as name, description to get wider. Here is the method that I am attempting to use below but, it is not working.

BTW, I am calling this method when the ClientSizeChanged Event fires on the ListView. Not sure if that is relevant or not.

    public static void ResizeListViewColumns(ListView lv, List<int> fixedColumnIndexes, List<int> nonFixedColumnIndexes)
    {
        int lvFixedWidth = 0;
        int lvNonFixedWidth = 0;
        if (fixedColumnIndexes.Count + nonFixedColumnIndexes.Count != lv.Columns.Count)
        {
            throw new Exception("Number of columns to resize does not equal number of columns in ListView");
        }
        else
        {
            // Calculate the fixed column width
            // Calculate the non-fixed column width
            // Calculate the new width of non-fixed columns by dividing the non-fixed column width by number of non-fixed columns
            foreach (var fixedColumn in fixedColumnIndexes)
            {
                lvFixedWidth += lv.Columns[fixedColumn].Width;
            }

            foreach (var nonFixedColumn in nonFixedColumnIndexes)
            {
                lvNonFixedWidth += lv.Columns[nonFixedColumn].Width;
            }

            int numNonFixedColumns = nonFixedColumnIndexes.Count;
            foreach (var newNonFixedColumn in nonFixedColumnIndexes)
            {
                lv.Columns[newNonFixedColumn].Width = lvNonFixedWidth / numNonFixedColumns;
            }
        }
    }

Upvotes: 1

Views: 904

Answers (1)

Alan
Alan

Reputation: 7951

Something like this should for you... Instead of keeping a list of fixed and unfixed indices, in my example I set the "Tag" property of each fixed column to the string "fixed".

int fixedWidth = 0;
        int countDynamic = 0;

        for (int i = 0; i < listView1.Columns.Count; i++)
        {
            ColumnHeader header = listView1.Columns[i];

            if (header.Tag != null && header.Tag.ToString() == "fixed")
                fixedWidth += header.Width;
            else
                countDynamic++;
        }

        for (int i = 0; i < listView1.Columns.Count; i++)
        {
            ColumnHeader header = listView1.Columns[i];

            if (header.Tag == null)
                header.Width = ((listView1.Width - fixedWidth) / countDynamic);
        }

Upvotes: 1

Related Questions