在ListView EmptyDataTemplate中查找控件

Cal*_*ine 12 .net c# asp.net listview findcontrol

ListView喜欢这个

<asp:ListView ID="ListView1" runat="server">
   <EmptyDataTemplate>
      <asp:Literal ID="Literal1" runat="server" text="some text"/>
   </EmptyDataTemplate>
   ...
</asp:ListView>
Run Code Online (Sandbox Code Playgroud)

Page_Load()我有以下几点:

Literal x = (Literal)ListView1.FindControl("Literal1");
x.Text = "other text";
Run Code Online (Sandbox Code Playgroud)

但是x回归null.我想更改Literal控件的文本,但我不知道如何做到这一点.

小智 20

我相信,除非你在代码后面调用DataBind你的ListView某个方法,否则ListView永远不会尝试数据绑定.然后什么都不会渲染,甚至Literal不会创建控件.

在您的Page_Load活动中尝试以下内容:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        //ListView1.DataSource = ...
        ListView1.DataBind();

        //if you know its empty empty data template is the first parent control
        // aka Controls[0]
        Control c = ListView1.Controls[0].FindControl("Literal1");
        if (c != null)
        {
            //this will atleast tell you  if the control exists or not
        }    
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法在数据绑定方法中这样做?我宁愿*不*硬编码"控件[0]",因为它很草率. (4认同)