DataGridView - how to set column width?

后端 未结 13 2293
情书的邮戳
情书的邮戳 2020-12-13 23:58

I have a WinForms application with DataGridView control. My control has five columns (say \"Name\", \"Address\", \"Phone\" etc)

I am not happy with defa

13条回答
  •  自闭症患者
    2020-12-14 00:48

    i suggest to give a width to all the grid's columns like this :

    DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
    col.HeaderText = "phone"            
    col.Width = 120;
    col.DataPropertyName = (if you use a datasource)
    thegrid.Columns.Add(col);    
    

    and for the main(or the longest) column(let's say address) do this :

    col = new DataGridViewTextBoxColumn();
    col.HeaderText = "address";
    col.Width = 120;
    

    tricky part

    col.MinimumWidth = 120;
    col.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
    

    tricky part

    col.DataPropertyName = (same as above)
    thegrid.Columns.Add(col);
    

    In this way, if you stretch the form (and the grid is "dock filled" in his container) the main column, in this case the address column, takes all the space available, but it never goes less than col.MinimumWidth, so it's the only one that is resized.

    I use it, when i have a grid and its last column is used for display an image (like icon detail or icon delete..) and it doesn't have the header and it has to be always the smallest one.

提交回复
热议问题