Creating dynamic buttons on a TabPage

MrPNW

New member
Joined
Jul 23, 2025
Messages
2
Programming Experience
10+
I have a WinForm in which I have multiple TabControls. Each tab is show/hidden based on a main-menu click. What I need to do is dynamically create an "Exit" button for each TabPage of each TabControl and then associate each button with a specific Btn_Click() event or multiple ones if need be. I'm doing this in C# which I'm new to. H E L P ! ! !

Thanks in advance
 
You would simply add a new Button to the Controls collection of that tab page in your code. The Button.Click event can accept more than one event handler.

See how to add controls using code:

Or how to add controls at runtime:
 
Here is an example that placed a Button, bottom right, on each TabPage.

C#:
Expand Collapse Copy
public class SpecialButton : Button
{
    public SpecialButton()
    {
        Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
        Text = "Exit";
        Size = new(95, 29);

        ParentChanged += OnParentChanged;
    }

    private void OnParentChanged(object sender, EventArgs e)
    {
        if (Parent is not TabPage tabPage) return;
        var margin = 10;
        Location = new(tabPage.ClientSize.Width - Width - margin, tabPage.ClientSize.Height - Height - margin);

        tabPage.SizeChanged += (s, ev) =>
        {
            Location = new(tabPage.ClientSize.Width - Width - margin, tabPage.ClientSize.Height - Height - margin);
        };
    }
}

C#:
Expand Collapse Copy
public partial class FormButtons : Form
{
    public FormButtons()
    {
        InitializeComponent();

        Shown += FormButtons_Shown;

    }

    private void FormButtons_Shown(object sender, EventArgs e)
    {
        foreach (TabPage page in tabControl1.TabPages)
        {
            var specialButton = new SpecialButton { Name = $"{page.Name}CloseButton" };
            specialButton.Click += SpecialButton_Click;
            page.Controls.Add(specialButton);
        }
    }

    private void SpecialButton_Click(object sender, EventArgs e)
    {
        var text = (sender as SpecialButton)?.Name;
        // TODO: Handle the button click event
    }
}
 
The key lines are lines 16 and 17 of the second chunk of code presented by @kareninstructor . They setup the event handler and the add the button.
 

Latest posts

Back
Top Bottom