如何在LayoutTemplate
控件的ListView
中访问控件?
我需要转到litControlTitle
并设置其Text
属性。
<asp:ListView ID="lv" runat="server">
<LayoutTemplate>
<asp:Literal ID="litControlTitle" runat="server" />
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
</ItemTemplate>
</asp:ListView>
有什么想法?也许是通过OnLayoutCreated
事件?
答案 0 :(得分:35)
试试这个:
((Literal)lv.FindControl("litControlTitle")).Text = "Your text";
答案 1 :(得分:17)
完整的解决方案:
<asp:ListView ID="lv" OnLayoutCreated="OnLayoutCreated" runat="server">
<LayoutTemplate>
<asp:Literal ID="lt_Title" runat="server" />
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
</ItemTemplate>
</asp:ListView>
在代码背后:
protected void OnLayoutCreated(object sender, EventArgs e)
{
(lv.FindControl("lt_Title") as Literal).Text = "Your text";
}
答案 2 :(得分:4)
此技术适用于模板布局;使用控件的init事件:
<asp:ListView ID="lv" runat="server" OnDataBound="lv_DataBound">
<LayoutTemplate>
<asp:Literal ID="litControlTitle" runat="server" OnInit="litControlTitle_Init" />
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
</ItemTemplate>
</asp:ListView>
捕获对控件的引用,以便在ListView的DataBound事件中使用代码隐藏(例如):
private Literal litControlTitle;
protected void litControlTitle_Init(object sender, EventArgs e)
{
litControlTitle = (Literal) sender;
}
protected void lv_DataBound(object sender, EventArgs e)
{
litControlTitle.Text = "Title...";
}
答案 3 :(得分:0)
对于嵌套LV循环:
void lvSecondLevel_LayoutCreated(object sender, EventArgs e)
{
Literal litText = lvFirstLevel.FindControl("lvSecondLevel").FindControl("litText") as Literal;
litMainMenuText.Text = "This is test";
}
答案 4 :(得分:0)
如果您需要VB版本,这里是
Dim litControl = CType(lv.FindControl("litControlTitle"), Literal)
litControl.Text = "your text"