【问题标题】:Get the text of a label in a listview获取列表视图中标签的文本
【发布时间】:2014-08-06 07:01:34
【问题描述】:

我有一个列表视图控件,其中填充了数据库中的数据。我已经使用标签来显示该数据。现在我需要在其他地方使用该标签的值。我正在尝试访问标签控件的文本值,但它说

对象引用未设置为对象的实例。

但我的标签确实有价值。

<asp:ListView ID="msg_list" runat="server">
   <ItemTemplate>
    <table>
      <tr class="myitem">
        <td>
            <asp:Label ID="reg_id_reply" runat="server" Text="helo" Visible="false"  />
             <asp:Label role="menuitem" ID="msg_lbl" runat="server" text='<%#Eval("msg")%>' /><i style=" color:Gray; " >  from   
             <asp:Label ID="tme" runat="server" Text='<%#Eval("name")%>' />
             <i> on </i>
             <asp:Label ID="tmelbl" runat="server" Text='<%#Eval("tme")%>'/>
              <a id="msg-reply" class="btn button" data-toggle="modal" data-target="#msg-rply" style="cursor:pointer;" ><i class="glyphicon glyphicon-share-alt white"> </i></a>  </td>

              <hr style=" margin-top:1px; margin-bottom:1px; " />
      </tr>
     </table>
     <%--<hr style=" margin-top:1px; margin-bottom:1px; " />--%>
   </ItemTemplate>
  </asp:ListView>

这就是我尝试访问标签文本的方式。请注意,下面的代码位于按钮单击事件onClick 中。

Label mylbl = (Label)msg_list.FindControl("reg_id_reply");
string rid = mylbl.Text;

【问题讨论】:

  • 但是我在标签中有文本值,如您在上面看到的Text="helo"
  • 如果知道标签的ID,LabelID.Text会给出标签中的文本值
  • 是的,如果标签不在 ListView 内,但我在 ListView 内有该标签。
  • 是 foreach 循环中的 C# 代码吗?

标签: c# asp.net listview


【解决方案1】:

根据Control.FindControl Method (String)的描述:

只有当控件直接包含在指定容器中时,此方法才会找到控件。

您的标签所在的direct 容器是ItemTemplate。因此,如果您从列表视图开始,您可能需要为您的标签构建递归搜索。您可以尝试使用this MSDN page 建议的以下代码:

private Control FindControlRecursive(Control rootControl, string controlID)
{
    if (rootControl.ID == controlID) return rootControl;

    foreach (Control controlToSearch in rootControl.Controls)
    {
        Control controlToReturn = FindControlRecursive(controlToSearch, controlID);
        if (controlToReturn != null) return controlToReturn;
    }
    return null;
}

但也请注意,列表视图可能会更改项目模板中组件的 id 值。如果您知道您想要的项目索引,那么您可以使用this post中建议的方法:

var theLabel = this.ChatListView.Items[<item_index>].FindControl("reg_id_reply") as Label;

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多