0

I have the code below in the ItemDataBound event for a Repeater control:

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

I debugged the code but couldn't find why this line throws NullReferenceException:

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

I verified in the debugger that the object itemLiked is not null.

Here is the markup for the HTML button in the Repeater:

<button type="button" id="LikeButton" value='<%#Eval("PollQuestionID") %>' class='<%#GetCSS(Eval("PollQuestionID")) %>'>
    <span class="glyphicon glyphicon-thumbs-up"></span> <%#LikeText(Eval("PollQuestionID")) %>
</button>
Michael Liu
  • 52,147
  • 13
  • 117
  • 150
Kacey Ezerioha
  • 1,068
  • 4
  • 22
  • 46

1 Answers1

1

The FindControl method can only find server controls — those that have the runat="server" attribute. Add this attribute to your <button>:

<button runat="server" type="button" id="LikeButton" ...
Michael Liu
  • 52,147
  • 13
  • 117
  • 150