我有一个ascx控件,我使用FormView。在Child1控件上,一个下拉列表,我希望在子ascx上找到这个父ascx下拉列表值。下面是我尝试的代码,但我没有得到值。总是null
FormView _parentView = this.Parent.NamingContainer as FormView;
if (_parentView != null)
{
FormViewRow _row = _parentView.Row;
DropDownList _ddlOrg = DropDownList)_row.FindControl("DDL_Organization");
}页面类似于这个结构
父页面-- aspx
1child control - ascx
2child control - ascx 我想在第二个孩子上找到一个子值。
谢谢你的答复。
发布于 2014-08-14 14:40:48
定位DDL的最大困难是您使用的是FormView,因此在编译时不存在控件。
下面是添加到Child1中的一个属性,当您想要访问它时,它将查找并公开DDL。在您调用DataBind之前,这将是空的。
private DropDownList z_DDL_Organization = null;
/// <summary>
/// Expose the Organization DDL
/// </summary>
public DropDownList DDL_Organization
{
get
{
if (this.z_DDL_Organization==null)
this.z_DDL_Organization = FormView1.FindControl("DDL_Organization") as DropDownList;
return this.z_DDL_Organization;
}
}要在Child2控件中访问此控件,您需要首先定位Child1控件。由于FormView,Child1控件将不是Child2的直接父控件。下面是一个函数,用于搜索父链,直到找到Child1为止,还有一些代码显示了如何使用它。
protected void Button1_Click(object sender, EventArgs e)
{
Child1 c = LocateParent(this.Parent);
if (c == null)
throw new ApplicationException("Child2 does not have Child1 as a parent");
// do stuff...
DropDownList _ddlOrg = c.DDL_Organization;
}
/// <summary>
/// Search up the parent chain to find Child1
/// </summary>
/// <param name="control"></param>
/// <returns></returns>
Child1 LocateParent( Control control)
{
if (control == null) return null;
Child1 RC = control as Child1;
if (RC != null) return RC;
return LocateParent(control.Parent);
}https://stackoverflow.com/questions/25307528
复制相似问题