在Repeater中设置HtmlButton属性会抛出NullReferenceException

本文关键字:NullReferenceException 属性 HtmlButton Repeater 设置 | 更新日期: 2023-09-27 18:04:43

我在Repeater控件的ItemDataBound事件中有以下代码:

HtmlButton btnLike = (HtmlButton)e.Item.FindControl("LikeButton");
var itemLiked = new LikesService().GetByPostIdUserId(pollQ.PostId, new Guid(Membership.GetUser(this.Context.User.Identity.Name).ProviderUserKey.ToString()));
if (itemLiked != null)
    btnLike.Attributes["class"] = "btn btn-primary btn-sm";

我调试了代码,但找不到为什么这一行抛出NullReferenceException:

btnLike.Attributes["class"] = "btn btn-primary btn-sm";

我在调试器中验证了对象itemLiked不为空。

下面是Repeater中HTML按钮的标记:
<button type="button" id="LikeButton" value='<%#Eval("PollQuestionID") %>' class='<%#GetCSS(Eval("PollQuestionID")) %>'>
    <span class="glyphicon glyphicon-thumbs-up"></span> <%#LikeText(Eval("PollQuestionID")) %>
</button>

在Repeater中设置HtmlButton属性会抛出NullReferenceException

FindControl方法只能找到服务器控件—那些具有runat="server"属性的控件。将此属性添加到您的<button>:

<button runat="server" type="button" id="LikeButton" ...