简体   繁体   中英

How to pass value from Form to UserControl?

I need to pass a value from Form to UserControl.

I have tried to: 1.(and i make basketBox public) Form:

UserControlBasket us1 = new UserControlBasket();
public void button1_Click(object sender, EventArgs e)
{
    us1.basketBox.Text = g1.Name;
}

2. Form:

UserControlBasket us1 = new UserControlBasket();
public void button1_Click(object sender, EventArgs e)
{
    us1.Txt = g1.Name;
}

UserControl:

public string Txt
{
    get { return basketBox.Text; }
    set { basketBox.Text = value; }
}

3. And i have tried to do like here: Pass value from Usercontrol to Form

I expect that in basketBox(it is a textBox) will be value from a g1.Name;

I just add a Controls.Add(us1) and it solved my problem.

I am just summarizing the comments (from @Jimi) with my answer here. Both the number 2 and 3 Solutions are acceptable and correct by design principles. It seems that a different object of user control was accessed here instead of using the one that placed the from.

In your case, you should better use textbox, which is attached to page and dont use a UserControl.

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