TabControl
manages and displays a related collection of tabs that can contain controls and
components. We can add multiple pages in a single form and each page can
contain its individual set of controls that can displayed when that tab is
selected.
When
we add a TabControl in our form then
it will add three Tab Pages as default
pages and tabPage1 will be selected tab. We can remove any tabPage from that control or can add a new tabPage.
Create a tab page
To add a tab page we can use Add method of TabPages property. Following
line of code will add three tab pages without any control
tabControl1.TabPages.Add("Page1");
tabControl1.TabPages.Add("Page2");
tabControl1.TabPages.Add("Page3");
Inserting
a tabPage with a label control:
Label label = new Label(); //New labal control
label.Text = "This is the
control which will added to TabPage"; //set
text property of label
TabPage tabPage = new TabPage(); //
create a new tabpage
tabPage.Text = "Tab Page
1"; // set text property of
tabpage
tabPage.Controls.Add(label); //add label control to above tabpage
tabControl1.TabPages.Add(tabPage); //finally add tabpage to our tabcontrol
Remove a tab page
To remove a tab page we can use Remove method of TabPages property. Using following line
of code we can remove selected tab from our tabControl:
tabControl1.TabPages.Remove(tabControl1.SelectedTab);
Load
tabpages from Database
In
the following example we will add tabPage according to our departments. Each
tab contains a list of employees working in that department. For showing list
of employees we used a DataGridView in a UserControl. When we add a tabPage then we will load userControl in that tabPage.
Step
1:
Create
two tables i.e. Department and Employee (described in previous article) in
our database.
Step
2:
Step
3:
Add
a UserControl to our project and then
add a DataGridView that will contain
list of employees. Write following code in constructor of UserControl:
public EmployeeUserControl(Department dept)
{
InitializeComponent();
DataContext dc = new DataContext();
var employees = from temp in dc.Employee
where temp.Department.Name == dept.Name
select new
{
temp.Name,
temp.Email,
temp.Mobile
};
empDataGridView.DataSource =
employees.ToList();
}
As in
above code datagridview will bind to the list of employees according to
department.
Step
4:
Now
finally in our form’s constructor write below line of codes to add pages to
tabControl
foreach (var item in dc.Department)
{
TabPage newTab = new TabPage(item.Name);
newTab.Controls.Add(new EmployeeUserControl(item));
tabControl1.TabPages.Add(newTab);
}
Download Source