Buddhi Dananjaya
Buddhi Dananjaya

Reputation: 641

Keep control back color after postback

I am changing back color of a Combo box when it has a value other than first value. (selectedindex = 0)

 <asp:DropDownList ID="ddlActive" runat="server" onchange="ChangeBackColor(this);">

js to change the color;

function ChangeBackColor(source) {
            if (source.selectedIndex > 0)
                source.style.backgroundColor = "LightGreen";
            else
                source.style.backgroundColor = "White";
        }

On that page there is a button, once click on that it reloads the page. I was able to preserve value using ViewStates.

<asp:Button ID="btnUpdate" runat="server" Text="Update" CssClass="btn"
                                                    OnClick="btnUpdate_Click" />

But back color has gone back to default (white), I need to preserve that too. What can I do for that?

Upvotes: 0

Views: 621

Answers (3)

Alex Kudryashev
Alex Kudryashev

Reputation: 9470

In your btnUpdate_Click (or in page_preRender) handler add line.

ScriptManager.RegisterStartupScript(this, this.GetType(), "ddlActiveColor",
   "ChangeBackColor(document.getElementById('" + ddlActive.ClientID + "'));", true);

If you do it in page_preRender then it is good idea to wrap this string into

if(page.IsPostBack({
   //ScriptManager...
}

Upvotes: 1

kennasoft
kennasoft

Reputation: 1593

Add this to the body tag:

<body onload="ChangeBackColor(document.getElementById(dropdownID))">

That should do what you want.

If you are using jQuery, do:

<script>
    jQuery(function(){
        ChangeBackColor(jQuery('#dropdownID'));
    });
</script>

Upvotes: 1

Antoine Pelletier
Antoine Pelletier

Reputation: 3316

in your page load event in the code behind, verify the selected value of your drop down list and set it to red on certain condition.

protected void Page_Load(object sender, EventArgs e)
{
    if(ddl.selectedvalue != "whatever")
         ddl.BackColor = function_that_return_a_color();
}

Upvotes: 1

Related Questions