简体   繁体   中英

Share a button with multiple pages in a Tab Control in Windows Forms

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 .

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):

    在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM