Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
protected void Button1_Click(object sender, EventArgs e)
{
    Button1.Attributes.Add("style", "background-color: #0066FF");
}

i click button but dont change color but i click twice change color. But i want change color first click
Posted
Updated 6-Jul-15 22:14pm
v4

1 solution

The events actually take place after the render of the control. This change would only be picked up on the second page reload so the render knows to add this attribute.

Instead make the change at the client side using javascript or try to intercept the event on page load or init.

Making the change on the client side would not persist after a page reload unless you are performing a partial postback: How to enable partial rendering with the AJAX UpdatePanel[^]. The button would have to be an external trigger otherwise it would get re-rendered.

Intercepting the button click on page load or init isn't too tricky. You need to get the Request.Form["__EVENTTARGET"]; which is the unique id of the control that triggered the postback. I use this in itembound repeaters because I prefer to have all of my backend code in c#. I hardly ever use asp.net in the markup.

Your code might look like this:
C#
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    var requestTarget = Request.Form["__EVENTTARGET"];

    var btnUniqueId = Button1.UniqueID;

    if(requestTarget == btnUniqueId)
         Button1.Attributes.Add("style", "background-color: #0066FF");
}


This will set the button colour once. There is no way included in this example to reset it, but it can be done simply enough.


Hope that helps ^_^
Andy
 
Share this answer
 
Comments
erdinccc 7-Jul-15 4:26am    
i dont understand sorry .
protected void Button1_Click(object sender, EventArgs e)
{
Button1.Attributes.Add("style", "background-color: #0066FF");
base.OnLoad(e);
var requestTarget = Request.Form["__EVENTTARGET"];

var btnUniqueId = Button1.UniqueID;

if (requestTarget == btnUniqueId)
Button1.Attributes.Add("style", "background-color: #0066FF");

}

is it? but this is not work
Andy Lanng 7-Jul-15 4:27am    
Read the answer carefully. It won't work in the Click event. Copy the method in the answer and paste in into your code
erdinccc 7-Jul-15 4:39am    
Thanks i solve this problem thanks a lot

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900