how to find control in ItemTemplate of the ListView from code behind of the usercontrol page?

老子叫甜甜 提交于 2019-11-28 06:20:47

问题


actually, i'm developing a web template using ASP.NET and C#. i have a listview in a usercontrol page and inside the ItemTemplate i have a PlaceHolder as below:

<asp:PlaceHolder ID="ph_Lv_EditModule" runat="server">  </asp:PlaceHolder>

i want to access to this PlaceHolder from code behind and i have use different method as below but i couldn't access it.

PlaceHolder ph_Lv_EditModule = (PlaceHolder)lv_Uc_Module.FindControl("ph_Lv_EditModule");

or

PlaceHolder ph_Lv_EditModule = (PlaceHolder)this.lv_Uc_Module.FindControl("ph_Lv_EditModule");

could you please help me how to find this control at the code behind of my usercontrol page. appreciate your consideration.


回答1:


A ListView typically contains more than one item, therefore the NamingContainer(searched by FindControl) of your Placeholder is neither the UserControl, nor the ListView itself. It's the ListViewItem object. So one place to find the reference is the ListView's ItemDataBound event.

protected void ListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        var ph_Lv_EditModule = (PlaceHolder)e.Item.FindControl("ph_Lv_EditModule");
    }
}

If you need the reference somewhere else, you must iterate the Items of the ListView and then use FindControl on the ListViewItem.

By the way, this is the same behaviour as in other DataBound Controls like GridView or Repeater.




回答2:


As Tim Schmelter mentioned, you can also access your control by iterating through your ListView as follows

private void HideMyEditModule()
{
    foreach (var item in lv_Uc_Module.Items)
    {
        PlaceHolder holder = item.FindControl("ph_Lv_EditModule") as PlaceHolder;
        if (holder!= null)
            holder.Visible = false;
    }
}


来源:https://stackoverflow.com/questions/9208528/how-to-find-control-in-itemtemplate-of-the-listview-from-code-behind-of-the-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!