访问ListView的LayoutTemplate内的控件

时间:2009-01-11 22:20:02

标签: c# asp.net listview asp.net-3.5

如何在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事件?

5 个答案:

答案 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"