Reputation: 2815
Is there a way to share a button with multiple pages in a C# Windows Forms Application; so that the button will be available in two or more pages?
I tried:
this.Page1.Controls.Add(this.Button1);
this.Page2.Controls.Add(this.Button1);
But it does not work for me and the button Button1
is still available only in Page1
.
Upvotes: 1
Views: 2123
Reputation: 125227
No you cannot share it, each control belongs to a single parent and cannot be shared between multiple parents. You can use either of the following options:
Use a single button but in tab selection change, move it to another tab page:
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
// Will be removed from previous tab and added to new selected tab
tabControl1.SelectedTab.Controls.Add(button1);
}
Use different buttons in each tab page but share the same event handler
button1.Click += button_Click;
button2.Click += button_Click;
...
private void button_Click(object sender, EventArgs e)
{
//var clicked = (Button)sender;
//Do somthing
}
Put it over the tab control, not inside the pages (pay attention to document outline):
Upvotes: 3