locked
How to change the CSS class for a div in code-behind? RRS feed

  • Question

  • User881333916 posted

    I would like to change the name of the CSS class for a div based on a decision made in code-behind.  The div looks likes this: 

    <div id="divAllItemList" runat="server" class="divAllItemList">
     I tried the following code but an error message states that control is null: 
                HtmlControl control = FindControl("divAllItemList") as HtmlControl;
                control.Attributes["class"] = "hidden";
     
    Monday, March 16, 2009 3:16 PM

Answers

  • User980627933 posted

    If your div has runat="server" then you directly use this:

    divAllItemList.Attributes["class"] = "hidden";

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 16, 2009 3:29 PM
  • User592294478 posted

    Change your <div> to an ASP.Net Panel (which creates an HTML div tag in the final markup) and then set it, like this:

    HTML Page: 
    <asp: Panel id="mypanel" runat="server" CssClass="showme">
         <p>blah blah</p>
    </asp: Panel>

     CodeBehind:
    protected void MyEvent(object sender, EventArgs e)
    {
         mypanel.CssClass = "hidden";
    }

    This allows you to change may aspects of the Panel programmatically, including adding or removing attributes.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 16, 2009 7:01 PM

All replies

  • User980627933 posted

    If your div has runat="server" then you directly use this:

    divAllItemList.Attributes["class"] = "hidden";

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 16, 2009 3:29 PM
  • User1831358492 posted

    As mentioned above, if you have the runat="server" tag specified you can reference the ID directly in code behind but if you still want to find your control, try this:

    C#
    HtmlGenericControl theDiv = new HtmlGenericControl("divAllItemList");

    VB
    Dim theDiv As HtmlGenericControl = New HtmlGenericControl("divAllItemList")

     

    Monday, March 16, 2009 3:30 PM
  • User881333916 posted

    I tried this and it worked:  divAllItemList.Attributes["class"] = "hidden";

    The strange thing is that while it it sets it to "hidden" OK (which contains display: none), the div remains hidden even after I reset it to its original CSS rule.  I put display: block in the rule to no effect.

    Monday, March 16, 2009 6:35 PM
  • User1831358492 posted

     Can you post some code here?

    Monday, March 16, 2009 6:47 PM
  • User592294478 posted

    Change your <div> to an ASP.Net Panel (which creates an HTML div tag in the final markup) and then set it, like this:

    HTML Page: 
    <asp: Panel id="mypanel" runat="server" CssClass="showme">
         <p>blah blah</p>
    </asp: Panel>

     CodeBehind:
    protected void MyEvent(object sender, EventArgs e)
    {
         mypanel.CssClass = "hidden";
    }

    This allows you to change may aspects of the Panel programmatically, including adding or removing attributes.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 16, 2009 7:01 PM
  • User881333916 posted

    Here is the code.  Thanks for taking a look.
    There are 2 ListView controls in a Master / Detail relationship.  I want to hide the Detail ListView if the Master ListView has not selected a row yet.  It sets the class to "hidden" and that works OK -- everything inside divAllItemList disappears.  When the Master ListView does have a SelectedIndex it goes throught he code correctly.  I stepped through it and it does set the class back to the original class="divAllItemList".  However, the contents within the div do not re-appear. 

    Although I have stepped through the code that sets the class back to divAllItemList, when I do a View Source on the browser I still see class="hidden".  It hadn't been successfully reset to the original CSS rule.  Here's what I see in View source:
    <div id="ctl00_bodyContentPlaceHolder_divAllItemList" class="hidden">

    In addition, when I mouse over divAllItemList in code-behind using debugger, it displays:  {InnerText = '((System.Web.UI.HtmlControls.HtmlContainerControl)(((System.Web.UI.HtmlControls.HtmlGenericControl)(divAllItemList)))).InnerText' threw an exception of type 'System.Web.HttpException'}
    Yet it doesn't actually throw an error.  The code never goes into the catch.

    The code-behind always works the first time, no matter which CSS rule you set it to.  But it will not work after that.  Once it has been set by code-behind, it can't be set again to another rule.  Could it be caching the first change and continuing to use it despite the fact that the program runs code to change it?  Does it create a new object each time it runs it, and continues to use the first object?

    Here is the code:

    <div id="divAllItemList" runat="server" class="divAllItemList">
                <asp:UpdatePanel ID="up_tcItemList" runat="server" UpdateMode="Conditional">
                    <ContentTemplate>
                        <cc1:TabContainer ID="tcItemList" runat="server" ActiveTabIndex="0" ScrollBars="None"
                            TabStripPlacement="Top">
                            
                            <!-- TAB: TEXT -->
                            <cc1:TabPanel ID="tpText" runat="server" HeaderText="Text">
                                <ContentTemplate>
                                    <div class="divTextItemWrapper">
                                        <asp:Button ID="btnAddText" runat="server" CssClass="btnAddItem" OnClick="btnAddText_Click"
                                            Text="Add new text" Enabled="false" />
                                        <asp:Button ID="btnDoNothing3" runat="server" CssClass="hidden" Text="Hide" />
                                        <cc1:ModalPopupExtender ID="mpe_AddText" runat="server" BackgroundCssClass="modalBackground"
                                            DynamicServicePath="" Enabled="True" OkControlID="btnAddTextItem_OK" PopupControlID="pnlAddTextItem"
                                            TargetControlID="btnDoNothing3">
                                        </cc1:ModalPopupExtender>
      
    .divAllItemList
    {
        display: block;
        position: relative;
        width: auto;
        height: auto;
        margin-left: auto;
        margin-right: auto;
        text-align: left;
        padding: 0.2em 0.2em 0.2em 0.2em;
        background-color: White;
        border-color: #555555;
        border-style: solid;
        border-width: 0px;
    }
    .hidden
    {
        display:none;
    }
      
        protected void lvFoundNotes_DataBound(object sender, EventArgs e)
        {
            // If no row is selected from Found Notes, hide the detail controls.
            if (lvFoundNotes.SelectedIndex < 0)
            {
                try
                {
                    divAllItemList.Attributes["class"] = "hidden";
                }
                catch (HttpException ex)
                { string abc = ex.Message; }
                catch (Exception ex)
                { string abc = ex.Message; }
            }
            else
            {
                try
                {
                    divAllItemList.Attributes["class"] = "divAllItemList";
                }
                catch (System.Web.HttpException ex)
                { string abc = ex.Message; }
                catch (Exception ex)
                { string abc = ex.Message; }
            }
        }
     
    Monday, March 16, 2009 7:15 PM
  • User881333916 posted

    mbielski, is there really an advantage to using an ASP.NET panel instead of a div?  I just replaced a bunch of panels with divs with the hopes of making the code cleaner.  I had a problem with panels.  I had to set the height, where with a div I didn't.  But maybe that's because my CSS positioning skills were evolving at the same time.  The next thing I will want to do is to change values for CSS properties within code-behind.  Is that do-able with ASP.NET controls like panels, but not do-able with divs?

    Monday, March 16, 2009 7:45 PM
  • User881333916 posted

    amitchandnz, I tried this and it did not change the CSS rule to "hidden".  Am I missing something?

    HtmlGenericControl theDiv = new HtmlGenericControl("divAllItemList");
    theDiv.Attributes[
    "class"] = "hidden";

    Monday, March 16, 2009 8:23 PM
  • User592294478 posted

    mbielski, is there really an advantage to using an ASP.NET panel instead of a div?  I just replaced a bunch of panels with divs with the hopes of making the code cleaner.  I had a problem with panels.  I had to set the height, where with a div I didn't.  But maybe that's because my CSS positioning skills were evolving at the same time.  The next thing I will want to do is to change values for CSS properties within code-behind.  Is that do-able with ASP.NET controls like panels, but not do-able with divs?

    When it comes to changing the assigned CSS classes for a div, I have had much better results using the panel. Height tends to be a problem in IE if you are using positioning of any kind, even something as simple as float:left. You might check out the CSS specs over at www.w3schools.com and note anywhere that it says that the result is to remove the item from the regular layout and position it separately, either in or out of the original container. If you are wanting to change values within the CSS, my choice would be to make several small CSS classes and do the assignments you need with them. If somebody can tell you how to do it via codebehind, I'd be happy to try it myself as I've never done it.

    Sample CSS

    .bold
    {
         font-weight:bold;
    }

    .red
    {
         color:red;
         background-color:white;
    }

    The CSS assignment: mypanel.CssClass = "bold red";

    This will make your text both bold and red. You just have to remember to put a space between classes, or JS will think you are calling some other class. Using this and several other small CSS classes, you can do pretty much whatever you need. If somebody has a better way, I'm all for it!

    Monday, March 16, 2009 8:49 PM
  • User881333916 posted

    Thank you for the replies.  I found out how to change the CSS rule for a DIV, even though it only works the first time.  I have created a new thread that describes that problem (and its solution!) here:  http://forums.asp.net/t/1398010.aspx

    Tuesday, March 17, 2009 10:37 AM
  • User1541097065 posted

    Hello,

    Can you give an example with out "runat=server" attribute of the div?

    Wednesday, January 29, 2014 8:09 AM