开发者

Determine ClientID of ContentPlaceHolder in current context when adding dynamic controls

I am creating a Table Control on-the-fly, which contains a series of Labels and Dropdowns for each row of the table which also includes some javascript on the labels and dropdowns.

    Dim dd As New DropDownList
    Dim ds As System.Data.DataTable = GetTable("EmployeePosition")
    Dim prefix As String = "Position"
    dd.ID = prefix & i
    dd.DataSource = ds
    dd.DataValueField = "PositionID"
    dd.DataTextField = "PositionName"
    dd.Attributes.Add("onchange", "checkDuplication(this,'" & prefix & "');")
    dd.DataBind()

The javascript function 'onchange' loops through all dropdown controls starting with the prefix and checks if the value of any of the dropdowns is the same.

This table is then added into a PlaceHolder control, which in turn is contained in a ContentPlaceHolder control which is开发者_高级运维 on my Master Page.

    Master_Content1_Position1

The problem I have reoccuring is the automatic naming of controls when placed on Master Pages and ContentPlaceHolders, particularly when it involves javascript.

The best solution I have come up with so far is to find the ContentPlaceHolder which will contain the PlaceHolder, retrieve the ClientID and pass that value onto the table creator.

        Dim cph As ContentPlaceHolder = Me.Master.FindControl("Content1")
        Dim tbl As Table = New PositionTable(cph.ClientID).ToTable
        PlaceHolder1.Controls.Add(tbl)

Is there a way to determine what the current ContentPlaceHolder a Control or PlaceHolder is in, and to return the ClientID or UniqueID so I can pass this value to my Table creator to prefix the javascript functions to point to the right controls using the Element ID? Preferably, using the PlaceHolder or Control that will be populated as a base value?

Thanks.


You can use the Parent property of Control class. That will return ContentPlaceHolder control if your control is first level child of it. If not, then you could take Parent of Parent (and so on) and check whether it is ConterPlaceHolder:

private ContentPlaceHolder GetParentContentPlaceHolder()
{
    Control nextParent = this.Parent;
    while (nextParent != null)
    {
        ContentPlaceHolder parentContentPlaceHolder = nextParent as ContentPlaceHolder;
        if (parentContentPlaceHolder != null)
        {
            return parentContentPlaceHolder;
        }

        nextParent = nextParent.Parent;
    }

    return null;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜