问题
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