在ListView的LayoutTemplate中访问控件

23

如何访问 ListView 控件的 LayoutTemplate 中的控件?

我需要访问 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个回答

35

尝试这个:

((Literal)lv.FindControl("litControlTitle")).Text = "Your text";

我最初尝试了那个,但是没有成功。然后我来到这里。谢谢你! - craigmoliver
3
很奇怪......我把这段代码放在OnLayoutCreated的回调函数里,在绑定ListView时它能正常工作... - tanathos
嗯,我还没有把它放到那个事件里,现在试一下。 - craigmoliver
9
如果您正在阅读这个答案,请确保在ListView绑定到源(即,在ListView上调用DataBind后)之后调用FindControl。否则,在查找控件时,ListView的布局模板可能尚未就绪,因此FindControl将无法成功。请注意,不要更改原意。 - asm00
另外,如果数据绑定发生在空集合上,则无法找到控件。针对此情况进行空引用检查。 - John K

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";
}

这个解决方案比tanathos的更稳定。当DataBind和访问在同一个方法中时,tanathos的有时会出现问题。 - Gqqnbig

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...";
}

0

如果您需要VB版本,这里是它

Dim litControl = CType(lv.FindControl("litControlTitle"), Literal)
litControl.Text = "your text"

0

关于嵌套LV循环:

void lvSecondLevel_LayoutCreated(object sender, EventArgs e)
{
    Literal litText = lvFirstLevel.FindControl("lvSecondLevel").FindControl("litText") as Literal;
    litMainMenuText.Text = "This is test";
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接