Syed Salman Raza Zaidi
Syed Salman Raza Zaidi

Reputation: 2192

DataList ItemCommand Event changing CSS class

I have buttons in DataList control, when I click on a button, I am changing its CSS class in itemcommand event,the class is changing as expected, but when I click on button1 it will change its CSS class and after that I click on button2 it will also change its CSS class, but button1 also have same class, I want to add this class only on the button which I have clicked. this is my aspx code

 <asp:DataList ID="lst" runat="server" OnItemCommand="lst_ItemCommand"
                        Width="187">
                        <HeaderTemplate>
                        </HeaderTemplate>
                        <ItemTemplate>
                            <div class="num">
                                <asp:LinkButton  style="text-decoration:none;" ID="lnk" CommandName="detail" CommandArgument='<%# Eval("UserID") %>'
                                    runat="server"><%# Eval("Title")+" "+Eval("Firstname")%></asp:LinkButton>
                            </div>
                        </ItemTemplate>
                        <FooterTemplate>
                        </FooterTemplate>
                    </asp:DataList>

and this is my .CS code

   protected void lst_ItemCommand(object source, DataListCommandEventArgs e)
        {

            if (e.CommandName == "detail")
            {
            LinkButton btnlnk = (LinkButton)e.Item.FindControl("lnk");
                btnlnk.CssClass = "selectedclass";
              }


        }

Upvotes: 0

Views: 1580

Answers (2)

Damith
Damith

Reputation: 63065

you can do something like below

protected void lst_ItemCommand(object source, DataListCommandEventArgs e)
{
    if (e.CommandName == "detail")
    {
        int index = e.Item.ItemIndex;

        for (int i = 0; i < lst.Items.Count; i++)
        {
            LinkButton btnlnk = lst.Items[i].FindControl("lnk") as LinkButton;
            if (btnlnk !=null)
            {
                btnlnk.CssClass = index == i? "selectedclass" :string.Empty;
            }

        }

    } 
}

Upvotes: 1

kaanbasli
kaanbasli

Reputation: 1

You should to add AutoPostBack option for LinkButton and have to check page postback status (isPostBack). Because, your code will be regenerate for each postback.

Upvotes: 0

Related Questions