我有一个场景,我在webform中动态加载2个用户控件,并需要它们一起进行交互。这是代码:
default.aspx.cs
ControlA cA = (ControlA)LoadControl("~/controlA.ascx");
ControlB cB = (ControlB)LoadControl("~/controlB.ascx");
Page.Controls.Add(cA);
Page.Controls.Add(cB);
现在问题是,controlB需要将数据传递给controlA。数据不是来自事件(很好的一部分)。当用户单击来自controlB的链接时,我们从数据库获取数据,而我需要传递给controlA的是从请求中获取的第一个数据的ID。当然,当用户点击controlB中的链接时,页面会进行回发。
我看了一下事件&代表们,但我不能让它发挥作用。这是正确的方法吗?
如果有人能够提供线索,我们将非常感激!
答案 0 :(得分:1)
想到一个快速而又脏的方法是将第一个数据提取的ID声明为ControlB的公共属性,并在controlB上的链接回发处理程序上设置该值 例如。 在ControlB的事件处理程序:
public void Link_click(object sender, EventArgs e)
{
this.FirstFetchedId = GetValueFromDB();
}
然后在ControlA的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);
}