如何在子ascx上找到父ascx值

时间:2014-08-14 11:58:48

标签: asp.net c#-4.0 formview

我有一个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");

               }

Page就像这个结构

  

父页面 - aspx

   1child control - ascx
        2child control - ascx 

我想在第二个孩子身上找到1个孩子的价值

感谢您的回复。

1 个答案:

答案 0 :(得分:0)

查找DDL的最大困难在于您使用的是FormView,因此控件在编译时不存在。

这是您添加到Child1的属性,当您想要访问它时,它将查找并公开DDL。在您调用DataBind之前,这将为null。

    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);
    }