C# – Changing user control css class in code behind

asp.netcuser-controls

So I have a user control that displays links and I want to change the color of the link that is currently active.
This is the code inside my ListView of my usercontrol ascx file.

<asp:ListView ID="sidebarListView" runat="server" DataKeyNames="Id" DataSourceID="SqlDataSourceSidebar" OnItemCommand="sidebarListView_ItemCommand">
<ItemTemplate>
  <div id="sidebarItemID" class="sidebarItem" runat="server">
     <div>
        <asp:LinkButton ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' CommandName="Select" CommandArgument='<%# Eval("Id") %>' />
     </div>
  </div>
</ItemTemplate>
....

I need to change the sidebarItemID class when the linkbutton is clicked.
My default.aspx code behind looks like this:

private void SideBar1_ItemCommand ( object sender , EventArgs e ) {
  Int32 facId = Sidebar1.FacultyId;
  SqlDataSource1.SelectCommand = "SELECT [Id], [Name], [Faculty_Id], [User_Id], [Author], [Picture], [Location] FROM [Books] WHERE [Faculty_Id]=" + facId + " ORDER BY [DateAdded] DESC";
  HtmlGenericControl htmlDivControl = (HtmlGenericControl) FindControlRecursive( Sidebar1 , "sidebarItemID" );
  htmlDivControl.Attributes.Add("class", "sidebarItemActive");
  string newClass = htmlDivControl.Attributes["class"];
  //Response.Write( String.Format( "<script>alert('{0}');</script>" , newClass ) );
}

This correctly changes the sqlDataSource based on the ID of the link clicked in the user control. However the class doesn't change.

If I uncomment the Response.Write(…) section it correctly gives an alert that says "sidebarItemActive" so it correctly finds the control from my page and assigns its class attribute as "sidebarItemActive" but nothing changes on the page if I view the page source in the browser it says the class is still "sidebarItem".
What is going on here that the change does not come into effect?

Best Answer

The actual <div>s on your page are generated during the Render state of the ASP.NET Page Life Cycle. This happens after the Control event handling stage, thus any changes you make to the HTML during your handler function are effectively undone during Render, as the control's HTML is regenerated from the template. To have the control change its internal HTML in this case, you may put your update code in an overridden Render function for your control. The MSDN has an example of how to write the render function.

Related Topic