c# - 在运行时隐藏标签

标签 c# asp.net

我正在尝试将标签隐藏在转发器中。

<td>
   <div>
      <asp:Repeater ID="rpt1" runat="server" 
                    OnItemDataBound="rpt1_ItemDataBound">
            <HeaderTemplate>
               <table>
                  <tr>
                     <td>
                        <div>
                           <label id="lbl1"  runat="server">
                              <b>Project</b>
                            </label>
                        </div>
                     </td>
                  </tr>
               </table>
            </HeaderTemplate>
        </asp:Repeater>
    </div>
</td>

我想动态隐藏Label lbl1。

protected void rpt1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            //IT COMES HERE
            Label label = e.Item.FindControl("lbl1") as Label;
            label.Visible = false;
            // ERROR: OBJECT REFERENCE NOT SET TO AN INSTANCE OF AN OBJ
        }
    }

在这里,当我尝试调试代码时,它进入了循环,但给我的对象引用未设置为对象错误的实例。

更新

如果我尝试,

  HtmlGenericControl label = e.Item.FindControl("lbl1") as HtmlGenericControl;
            label.Visible = false;

有效

最佳答案

将您的标签转换为 asp:Label with a runat="server"

 <asp:label id="lbl1" runat="server">

或者保持你写的那样并在你的codebihind中添加runat="server"

HtmlGenericControl label = e.Item.FindControl("lbl1") as HtmlGenericControl;

关于c# - 在运行时隐藏标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28730466/

相关文章:

c# - SQL Server 数据库更改监听器 C#

c# - 服务器不接受在 HttpClientHandler 上设置的证书

c# - 将 VB6 与 COM Interop (C#) 结合使用时的意外事件行为

c# - 使用C#循环插入数据

c# - 如何从图像/位图对象返回图像作为 IActionResult

c# - 需要帮助将 Kendo TreeView 绑定(bind)到本地数据源

c# - XDocument 到字符串 : How to omit encoding in declaration?

c# - 如何在图像 map 上为 asp 热点着色?

javascript - JQuery:获取RadioButtonList中的每个项目

c# - 在 IIS 中运行时无法显示消息框?