C# – Add tabs to an existing tab control in WPF C#

ctabswpf

I am trying to add Tabs to a tab control in WPF but nothing appears on the control at runtime. I have tried following the examples I keep seeing. Right now this is what I have but it isn't working

_myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
    MessageBox.Show(myReader["SectionName"].ToString());
    TabItem newTabItem = new TabItem
    {
        Header = myReader["SectionName"].ToString(),
        Name = myReader["SectionID"].ToString()
    };
    TabMain.Items.Add(newTabItem);
}
_myConnection.Close();
TabMain.SelectedIndex = 0;

Best Answer

You can add tabs dynamically by using the following code.

Add the following code to declare tab control instance globally.

TabControl tbControl;

Now, add the following code to the loaded event of the tab control.

private void tbCtrl_Loaded(object sender, RoutedEventArgs e)
        {
            tbControl = (sender as TabControl);
        }

I have used a button to add new tabs for the existing tab control.

private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            TabItem newTabItem = new TabItem
            {
                Header = "Test",
                Name = "Test"
            };
            tbControl.Items.Add(newTabItem);
        }

Following is my tab control xaml view.

<TabControl  x:Name="tbCtrl" HorizontalAlignment="Left" Height="270" Margin="54,36,0,0" VerticalAlignment="Top" Width="524" Loaded="tbCtrl_Loaded">
            <TabItem Header="Tab - 01">
                <Grid Background="#FFE5E5E5">
                    <Button x:Name="btnAdd" Content="Add New Tab" HorizontalAlignment="Left" Margin="68,95,0,0" VerticalAlignment="Top" Width="109" Height="29" Click="btnAdd_Click"/>
                </Grid>
            </TabItem>
        </TabControl>

Finally, using this you can add any amount of tabs dynamically to the existing tab control.

Hope this fulfill your need.