Problem with dynamic tab creation in Winforms TabControl

I want to create dynamic tabs in TabControl. In each tabPage, I create a dataGridView, and I want to fill the entire space of each tab with this DataGrid. Here is the code where I do this:

private void tabControlMutants_SelectedIndexChanged(object sender, EventArgs e) { DataGridView dgw = new DataGridView(); DataGridViewTextBoxColumn testCaseCol = new System.Windows.Forms.DataGridViewTextBoxColumn(); DataGridViewTextBoxColumn resultCol = new System.Windoows.Forms.DataGridViewTextBoxColumn(); // // dataGridView1 // dgw.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; dgw.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { testCaseCol, resultCol}); dgw.Location = new System.Drawing.Point(3, 3); dgw.Name = "dataGridView1"; dgw.AutoSize = true; dgw.Dock = System.Windows.Forms.DockStyle.Fill; dgw.TabIndex = 0; // // TestCaseColumn // testCaseCol.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; testCaseCol.HeaderText = "Test Case"; testCaseCol.Name = "TestCaseColumn"; // // ResultColumn // resultCol.HeaderText = "Result"; resultCol.Name = "ResultColumn"; tabControlMutants.TabPages[(sender as TabControl).SelectedIndex].Controls.Add(dgw); ((System.ComponentModel.ISupportInitialize)(dgw)).EndInit(); //fill dataGridView } 

But this will not work, because when I resize the main window, the data gridView doesn.t resize it (although the dock property is set to fill). Any ideas?

+4
source share
3 answers

Move the statement dgw.Dock = System.Windows.Forms.DockStyle.Fill; below the line tabControlMutants.TabPages[...].Controls.Add(dgw); . And maybe below EndInit (), I'm not sure.

And delete the line dgw.Location = ... because it is not needed.

Edit:

I just did a little test, and this should basically work. This means that the error is somewhere else, not shown in the code. Perhaps in the "fill lines" section.
I recommend that you remove parts of the code to resolve the error.

And you understand that you create Dgv every time a tab is selected, right? I assume this is a demo code.

+1
source

Remove dgw.AutoSize = true;

+1
source

First try adding a control, then set the Dock property

+1
source

Source: https://habr.com/ru/post/1305079/


All Articles