DataGridView - how to set column width?

后端 未结 13 2269
情书的邮戳
情书的邮戳 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:31
    DataGridView1.Columns.Item("Adress").Width = 60
        DataGridView1.Columns.Item("Phone").Width = 30
        DataGridView1.Columns.Item("Name").Width = 40
        DataGridView1.Columns.Item("Etc.").Width = 30
    
    0 讨论(0)
  • 2020-12-14 00:39

    I you dont want to do it programmatically, you can manipulate to the Column width property, which is located inside the Columns property.Once you open the column edit property you can choose which column you want to edit, scroll down to layout section of the bound column properties and change the width.

    0 讨论(0)
  • 2020-12-14 00:40

    Regarding your final bullet

    make width fit the text

    You can experiment with the .AutoSizeMode of your DataGridViewColumn, setting it to one of these values:

    None
    AllCells
    AllCellsExceptHeader
    DisplayedCells
    DisplayedCellsExceptHeader
    ColumnHeader
    Fill
    

    More info on the MSDN page

    0 讨论(0)
  • 2020-12-14 00:42

    or Simply you can go to the form and when you call the data to be displayed you set the property like datagridview1.columns(0).width = 150 datagridview1.columns(1).width = 150 datagridview1.columns(2).width = 150enter code here

    So simple worked so fine with me Bro

    0 讨论(0)
  • 2020-12-14 00:46

    I know this is an old question but no one ever answered the first part, to set width in percent. That can easily be done with FillWeight (MSDN). In case anyone else searching comes across this answer.

    You can set DataGridAutoSizeColumnMode to Fill in the designer. By default that gives each column FillWeight of 100. Then in code behind, on FormLoad event or after binding data to grid, you can simply:

    gridName.Columns[0].FillWeight = 200;
    gridName.Columns[1].FillWeight = 50;
    

    And so on, for whatever proportional weight you want. If you want to do every single column with numbers that add up to 100, for a literal percent width, you can do that too.

    It gives a nice full DataGrid where the headers use the whole space, even if the user resizes the window. Looks good on widescreen, 4:3, whatever.

    0 讨论(0)
  • 2020-12-14 00:46

    Use:

    yourdataView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
    
    0 讨论(0)
提交回复
热议问题