codebehind is not setting CssClass on a link button in a repeater

3.5k views Asked by At

New to webforms/c# I get a reference to the object in the onclick handler. The reference to the object exists in the Repeater_ItemDataBound method. After the curObj.CssClass = "XXXXX" has run the class object curObj is updated. The page renders without the CSS class applied to the object.

I assume this is due to the LinkButton CSS does not apply to the Anchor tag that gets rendered in the end.

So how do I apply the CSS class to the actual rendered Anchor from the code behind?

// my aspx
<asp:Repeater ID="Repeater1" runat="server" onItemDataBound="Repeater_ItemDataBound">
  <ItemTemplate>
    <asp:LinkButton ID="my_btn" runat="server" OnCommand="cmdSelect_click" CommandArgument='<%# Eval("value") %>'><%# Eval("value") %></asp:LinkButton>
  </ItemTemplate>
</asp:Repeater>



// my code behind
protected void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
  if (((MyObject)e.Item.DataItem).value == CurrentValue )
  {
    curObj.CssClass = "someCssClassHere";
  }
}

protected LinkButton curObj;
protected void cmdSelect_click(object sender, CommandEventArgs e)
{
  curObj = (LinkButton)sender;
  CurrentValue = int.Parse(e.CommandArgument.ToString())-1;
}
2

There are 2 answers

1
Emre On BEST ANSWER

I dont understand when/where you want to set cssclass..

If you want to set it in ItemDataBound:

    protected void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        LinkButton my_btn = (LinkButton)e.Item.FindControl("my_btn");
        if (my_btn != null) my_btn.CssClass = "someCssClassHere";
    }

or if you want to set after Click:

    protected void cmdSelect_click(object sender, CommandEventArgs e)
    {
        LinkButton my_btn = (LinkButton)sender;
        my_btn.CssClass = "someCssClassHere";
    }
0
sh1rts On

That's not quite how templated controls such as the Repeater work.

Firstly, you should do a FindControl inside ItemDataBound to find your LinkButton, and apply the CSS to the item that is found.

Secondly, you don't wire up events for controls inside a Repeater that way; instead you handle the ItemCommand event of the Repeater.

Can you post the code you're using to bind the repeater ? It would be useful to know what your DataSource is, then I can post something that works.

This post might help as well - Linkbutton inside Repeater for paging ASP.Net