htmlcssasp.netlinkbuttonasplinkbutton

Change class on span inside button as sender


I wonder if its possible to select the inside a specific LinkButton in code behind.

That I want to make is when the button is clicked the span inside the button should change class. I know i can change it if i set an ID on the span but i wonder if its possible to get the span by the button as sender.

The button:

<asp:LinkButton ID="btnAttestMonday" runat="server" CssClass="btn btn-success  btn-xs" OnClick="btnAttest_Click" CausesValidation="false"><span class="glyphicon glyphicon-ok" runat="server"></span></asp:LinkButton>

Code behind:

    protected void btnChangeAttest_Click(object sender, EventArgs e)
{
    LinkButton btn = (LinkButton)sender;

    switch (btn.CommandName)
    {
        case "Attest":
            updateAttestInDB(btn.CommandArgument.ToString(), true);
            btn.CommandName = "RemoveAttest";
            break;
        case "RemoveAttest":
            updateAttestInDB(btn.CommandArgument.ToString(), false);
            btn.CommandName = "Attest";
            break;
    }      
}

I want the span to change class inside the switch cases.

Thanks in advance!


Solution

  • Make the span a Label and you're done. Then you just need to access it via ID. However, if you don't want that you can access it via the LinkButton's Controls-collection:

    protected void btnAttest_Click(object sender, EventArgs e)
    {
        LinkButton btn = (LinkButton)sender;
        var span = (HtmlGenericControl) btn.Controls[0];
        span.Attributes["class"] = "newCssClass";
        // ...
    }
    

    Of course that fails at runtime if you will change the layout in future.