Reputation: 159
I have a button called Button1
, and I have the following code-behind:
string CS = ConfigurationManager.ConnectionStrings["EasyRozMoney_ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spTaskPerformed", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@TaskId", lblTaskId.Text);
cmd.Parameters.AddWithValue("@Email", Session["Email"].ToString());
cmd.ExecuteNonQuery();
Button1.BackColor = Color.Red;
Button1.Enabled = false;
lblTaskPerformed.Text = "Task Completed Successfully.";
}
Everything else works fine.The button gets disabled too but it doesn't change its background color. Any suggestions?
Upvotes: 0
Views: 997
Reputation: 30287
The inline style on your button is preventing the background color from showing up.
Here's why:
Consider the following ASPX code:
<asp:Button runat="server" ID="Button1" Text="Click Me!"
style="background-color: yellow;"/>
This will render the following HTML:
<input type="submit" id="MainContent_Button1" value="Click Me!"
style="background-color: yellow;">
When we add a BackColor
in the code behind, it prepends an inline style into the element's style attribute. Which produces this HTML:
<input type="submit" id="MainContent_Button1" value="Click Me!"
style="background-color:Red;background-color: yellow;">
So it inserts the red color, but then the original color immediately overrides it.
To solve this, in your ASPX, use the BackColor
property instead of using the background-color
inline style tag. Like this:
<asp:Button ID="Button1" runat="server" Text="Submit"
BackColor="#CC6600" style="background-color:#CC6600;"/>
ASP.NET will know how to properly override this when new colors are applied.
If you had to do this in JavaScript, You can use RegisterStartupScript
to send dynamic javascript code to the browser, but I suspect something else is at issue.
var script = "document.getElementById('" + Button1.ClientID + "').style.backgroundColor = 'red';";
ScriptManager.RegisterStartupScript(this, typeof(Page), "changecolor", script, true);
Upvotes: 3
Reputation: 193
This might be of some help:
JavaScript:
function changeColor(e) {
e.style.color = "red";
return false;
}
ASPX:
<asp:LinkButton ID="LinkButton1" OnClientClick="return changeColor(this);"
runat="server">LinkButton</asp:LinkButton>
Upvotes: 0
Reputation: 1708
You can try this. It might help you. I was facing same issue but i want to change text. You can change color using this.
Button1.Invoke(new System.Action(() => Button1.BackColor = Color.Red));
Upvotes: 0