简体   繁体   中英

How to access control inside parent control? (asp.net c#)

I have page with listview in it. There is label and dropdownlist in listview. I would like to access the text of label from ddlTags_Init() method. Code:

<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" 
        DataKeyNames="id_Image" onitemdatabound="ListView1_ItemDataBound">
        <ItemTemplate>
             <asp:Label ID="TagsLabel" runat="server" Text='<%# Eval("Tags") %>' />
             <asp:DropDownList ID="ddlTags" runat="server" OnInit="ddlTags_Init" >
             </asp:DropDownList>
        </ItemTemplate>
</asp:ListView>

Code behind:

protected void ddlTags_Init(object sender, EventArgs e)
{
       DropDownList ddlTags = (DropDownList)sender;
       Label lblTag = (Label)ddlTags.Parent.FindControl("TagsLabel");
       string text=lblTag.Text;
}

At the moment i am stuck with

Label lblTag = (Label)ddlTags.Parent.FindControl("TagsLabel");

Anyone knows what am i missing? Thanks, Jim

Assuming that there are more than 1 elements in the listview datasource, why don't you put your code in the ItemDataBound handler? I think that it should work.

Init is too early to get the bind value of Label. In other words, label value hasn't been bind yet.

Instead you might want to consider using ItemDataBound method.

<asp:ListView ID="ListView1" runat="server" 
     OnItemDataBound="ListView1_ItemDataBound" ...>
  ....
</asp:ListView>

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        var ddlTags = e.Item.FindControl("ddlTags") as DropDownList;
        var tagsLabel = e.Item.FindControl("TagsLabel") as Label;
    }
}

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