Search code examples
c#.netdatagridviewautosizetabpage

AutoResize DataGridView Columns on TabPages


I'm having a little bit problem with AutoResize on DataGridView. Im doing it this way :

 for (int i = 0; i < list.Count; i++)
 {
      tabControl_Rozliczenie.TabPages.Add("Page " + list[i]);
      var dataGridView = new DataGridView()
      {
           Name = "dataGridView_" + list[i],
           Dock = DockStyle.Fill
      };

      dataGridView.CellValueChanged += 
              new DataGridViewCellEventHandler(dataGridView_ety_CellValueChanged);
      dataGridView.CellFormatting += 
              new DataGridViewCellFormattingEventHandler(dataGridView_ety_CellFormatting);
      dataGridView.DataSource = dataTable;

      tabControl_Rozl.TabPages[i].Controls.Add(dataGridView);
      dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); 
      dgwList.Add(dataGridView);
 }

It's adding new TabPages and DataGridViews on them but this part :

 dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)

AutoResize only DataGridView on tabPage[0] = first page, on the rest of them it doesn't work.

Can some one help me with finding code problem?

Assumption is :

It has to AutoResize DataGridView on each TabControlPage.


Solution

  • TabControl has a nasty habit of preventing the children of unselected TabPages from doing their layout.

    So you'll need to select each TabPage before filling the DataGridView and setting its AutoResizeColumns property:

    tabControl_Rozliczenie.TabPages.Add("Page " + list[i]);
    tabControl_Rozliczenie.SelectedTab = tabControl_Rozliczenie.TabPages["Page " + list[i]];