DataGridView Column Widths as Percentage
Asked Answered
A

3

10

Is there any way to give each column in a DataGridView a percentage width of the total grid? I am currently using fixed widths but would like to give one column a 15% width, another one a 25% width, and so on so that 100% of the table is filled and resizes with the Grid.

Ailurophile answered 22/3, 2013 at 20:2 Comment(0)
C
19

Try using the DataGridViewColumn.FillWeight property. Basically you assign a weight to every column and the columns re-size according to those weights. The MSDN arcticle is not that great. See the below article for better explaination -

Presenting Data with the DataGridView Control in .NET 2.0—Automatic Column Sizing

Cumber answered 22/3, 2013 at 20:34 Comment(0)
B
5

Try this

    private void DgvGrd_SizeChanged(object sender, EventArgs e)
    {
        dgvGrd.Columns[0].Width = (int)(dgvGrd.Width * 0.2);
        dgvGrd.Columns[1].Width = (int)(dgvGrd.Width * 0.2);
        dgvGrd.Columns[2].Width = (int)(dgvGrd.Width * 0.4);
        dgvGrd.Columns[3].Width = (int)(dgvGrd.Width * 0.2);
        // also may be a good idea to set FILL for the last column
        // to accomodate the round up in conversions
        dgvGrd.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; 
    }
Byron answered 22/8, 2020 at 21:32 Comment(0)
C
2

Can use a value converter
This subtracts a parameter but you could have it divide by a parameter.

<local:WidthConverter x:Key="widthConverter"/>

<GridViewColumn Width="{Binding ElementName=lvCurDocFields, Path=ActualWidth, Converter={StaticResource widthConverter}, ConverterParameter=100}">



 [ValueConversion(typeof(double), typeof(double))]
    public class WidthConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // value is the total width available
            double otherWidth;
            try
            {
                otherWidth = System.Convert.ToDouble(parameter);
            }
            catch
            {
                otherWidth = 100;
            }
            if (otherWidth < 0) otherWidth = 0;

            double width = (double)value - otherWidth;
            if (width < 0) width = 0;
            return width; // columnsCount;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
Clinometer answered 22/3, 2013 at 20:33 Comment(1)
Thank you for the example code. I am sure this will be used by someone although I found the other answer much easier to implement. I appreciate your help though!Ailurophile

© 2022 - 2024 — McMap. All rights reserved.