简体   繁体   中英

Pass data between 2 dynamically loaded User control

I have a scenario where I dynamically load 2 user controls in a webform, and need them to interact together. Here's the code :

default.aspx.cs
ControlA cA = (ControlA)LoadControl("~/controlA.ascx");
ControlB cB = (ControlB)LoadControl("~/controlB.ascx");
Page.Controls.Add(cA);
Page.Controls.Add(cB);

Now the thing is, controlB needs to pass a data to controlA. Data is not from an event (well part of). When user click on a link from controlB, we get data from a DB, and what I need to pass to controlA is the ID of the first data fetch from request. And of course, when user click on the link in controlB, page do a postback.

I looked at events & delegates, but I can't make it to work. Is it the right way to go ?

If anyone could have a clue, it would be really appreciated !

A quick and dirty method that comes to mind is to declare that ID of the first data fetch as a public property of ControlB, and set that value on your link postback's handler on controlB Eg. On ControlB's event handler :

public void Link_click(object sender, EventArgs e)
{
 this.FirstFetchedId = GetValueFromDB();
}

Then on ControlA's PreRender :

protected override void OnPreRender(EventArgs e)
{
ControlB cB = this.Page.FindControl("ControlBId") as ControlB; // either by ID or loop trough controls to find it by type
var YourIdIsHere = cB.FirstFetchedId;
base.OnPreRender(e);
}

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