简体   繁体   中英

How to access textbox inside UserControl from another one

So I've MainPage Form and this form contains three UserControl newIngredient , recipeAcrhive , recipesCenter , I've tried to access visible property of recipesCenter from recipeAcrhive because I want to access textbox in recipesCenter then show recipesCenter the but this was useless and I've tried a lot of solutions like

The confusion here is recipeAcrhive disappears and recipesCenter remain invisible

First Solution

create new instance from MainPage then access recipesCenter using Controls property and access textbox then hide recipeAcrhive and finally show recipesCenter

frmMainPage frm = new frmMainPage();
frm.Controls["recipesCenter"].Controls["txtName"].Text = "Meet";
this.Visible = false;
frm.Controls["recipesCenter"].Visible = true;

Second Solution

create new instance from MainPage and RecipesCenter then access textbox using Controls property and hide recipeAcrhive finally add RecipesCenter's instance into MainPage Form controls

frmMainPage frm = new frmMainPage();
RecipesCenter rc = new RecipesCenter();
rc.Controls["recipesCenter"].Controls["txtName"].Text = "Meet";
frm.Controls.Add(rc);

Third Solution

create method in MainPage and inside this method I make recipeArchive with hide visibility and recipesCenter with show visibility and access this method from recipeArchive using MainPage instance

// inside MainPage
public void showRecipesCenter() {
    recipeArchive.Visible = false;
    recipesCenter.Visible = true;
}

// inside recipeArchive
frmMainPage frm = new frmMainPage();
frm.showRecipesCenter();

Anyone can help me and make my day

Finally I found solution, here is the code

    public partial class frmMainPage : Form {
        public frmMainPage() {
            InitializeComponent();
        }

        private static frmMainPage frm;

        public static frmMainPage Instance {
            get {
                if (frm == null)
                    frm = new frmMainPage();
                return frm;
            }
        }

        private void frmMainPage_Load(object sender, EventArgs e) {
            frm = this;
        }
   }

and inside your UserControl do this

    public partial class yourUserControl : UserControl {      
       frmMainPage.Instance.anotherUserControl.txtName.Text = "stackoverflow";
    }

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