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

后端 未结 24 3037
孤城傲影
孤城傲影 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:44

    This trick works for me:

    grd.DataSource = DT;
    
    //set autosize mode
    grd.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    grd.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    grd.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
    
    //datagrid has calculated it's widths so we can store them
    for (int i = 0; i <= grd.Columns.Count - 1; i++) {
        //store autosized widths
        int colw = grd.Columns[i].Width;
        //remove autosizing
        grd.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
        //set width to calculated by autosize
        grd.Columns[i].Width = colw;
    }
    

    What happens here is that you set autosize to whathever mode you need and then column by column you store the width it got from autosize calculation, remove autosizing and set width to value you stored before.

提交回复
热议问题