How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

后端 未结 24 3035
孤城傲影
孤城傲影 2020-11-29 18:03

I am populating a DataGridView control on a Windows Form (C# 2.0 not WPF).

My goal is to display a grid that neatly fills all available width with cells - i.e. no un

24条回答
  •  抹茶落季
    2020-11-29 18:37

    Another version of Miroslav Zadravec's code, but slightly more automated and universal:

        public Form1()
        {
            InitializeComponent();
            dataGridView1.DataSource = source;
            for (int i = 0; i < dataGridView1.Columns.Count - 1; i++) {
                dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            }
            dataGridView1.Columns[dataGridView1.Columns.Count].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
    
        }
    
        void Form1Shown(object sender, EventArgs e)
        {
            for ( int i = 0; i < dataGridView1.Columns.Count; i++ )
            {
                int colw = dataGridView1.Columns[i].Width;
                dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
                dataGridView1.Columns[i].Width = colw;
            }
        }
    

    I put second part into separate event, because I fill datagridvew in initialization of form and if both parts are there, nothing is changing, because probably autosize calculates widths after datagridview is displayed, so the widths are still default in Form1() method. After finishing this method, autosize does its trick and immediately after that (when form is shown) we can set the widths by second part of the code (here in Form1Shown event). This is working for me like a charm.

提交回复
热议问题