I have a C # VisualStudio application. Can I use the same DataGridView in several tabControl tabs and how to implement it?
2 answers
Hang up on TabControl event handling. From the old tab you will remove the dataGridView1, and add to the activated one.
public class Form1 : Form { public Form1() { InitializeComponent(); tabControl1.Selected += tabControl1_Selected; tabControl1.Deselected += tabControl1_Deselected; } public void tabControl1_Selected(object sender, TabControlEventArgs e) { e.TabPage.Controls.Add(dataGridView1); } public void tabControl1_Deselected(object sender, TabControlEventArgs e) { e.TabPage.Controls.Remove(dataGridView1); } } Or add in the designer:
private void InitializeComponent() { // ... this.tabControl1.Selected += new TabControlEventHandler(this.tabControl1_Selected); this.tabControl1.Deselected += new TabControlEventHandler(this.tabControl1_Deselected); // ... } - 21. Just do not need to subscribe to events and in the designer, and manually in the code. One thing is enough. Otherwise, the event will occur twice. 2.
Removenot necessary,Addis enough - the control cannot have two parents, so it will automatically be removed from the previous one. 3. It would be nice to clean the example: remove the unnecessaryForm_Load. - Alexander Petrov - Thank you made a change. - Sergei Sergeev
Sergey's example is quite working, however, I will give two more ways.
one.
You can place the DataGridView not on TabControl , but on the form itself, on top of the table control. At the same time, no event handlers are needed and there will be no flickering of the grid when switching tabs.
To do this, in the designer mode, you need to drag it to the empty space of the form (thus, the form will become the parent). Then in the properties of the data grid, manually set the desired coordinates by sliding it to TabControl . In this case, it may turn out that the grid will be lower in the z-order and will not be visible. Then you need to press the Bring to Front button on the toolbar.
If we create controls manually, instead of a string
// помещаем датагрид на табконтрол tabControl.TabPages[0].Controls.Add(dataGridView); need to write
// помещаем датагрид на форму this.Controls.Add(dataGridView); // задаём такие координаты, чтобы он был в нужном месте табконтрола dataGridView.Top = 50; dataGridView.Left = 20; // выводим его поверх других контролов dataGridView.BringToFront(); 2
On each tab we place our own component DataGridView . And all of them are tied to the same data source. Elementary! Now you can edit the data on any tab, and when you switch to another, they will be automatically updated thanks to the binding.
That is, the code will have something like:
tabControl.TabPages[0].Controls.Add(dataGridView1); tabControl.TabPages[1].Controls.Add(dataGridView2); dataGridView1.DataSource = source; dataGridView2.DataSource = source; Perhaps this method is the most correct.
visual-studiotag, please specifyWinFormsorWPF. - Bulson