FranticJ3 FranticJ3 - 6 months ago 12
CSS Question

Updating CSS of Controls in different files via CodeBehind

I have this AJAX button that I want to update some CSS. The problem is that the controls I want it to update are in a different file and can't be moved out of that file.

This is the panel whose CSS I want to update, which is located in the Site.master file:

<asp:ScriptManager ID="ScriptManager" runat="server" />
<asp:UpdatePanel ID="Panel2" runat="server" updatemode="Always">
<ContentTemplate>
<div id="updateThis" runat="server"><p>Test text</p></div>
</ContentTemplate>
</asp:UpdatePanel>


This is the button, located in the Items.ascx file:

<asp:UpdateProgress runat="server" ID="PageUpdateProgress">
<ProgressTemplate>
<img class="ajax-loader" src="/Images/ajax-loader.gif" alt="Loading..." />
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="Panel3" runat="server" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="UpdateButton" eventname="Click" />
</Triggers>
<ContentTemplate>

<asp:Button runat="server" OnClick="UpdateButton"
OnClientClick="hideButton()" Text="Update"
class="update" ID="UpdateButton" name="UpdateButton"
type="submit" ></asp:Button>

</ContentTemplate>
</asp:UpdatePanel>


This is the Items.ascx.cs method that is UpdateButton

protected void UpdateButton(object sender, EventArgs e)
{
var masterPage = this.Page.Master;
var updatePanel = masterPage.FindControl("Panel2");

var div = (HtmlGenericControl)updatePanel.Controls[0].FindControl("updateThis");
div.Style.Add("color", "#ff0000");
}


When I click the button it doesn't end up working correctly. As of right now, with the AJAX UpdateProgress template, it shows the loading GIF and then the GIF disappears and the text never changes color.

EDIT

Hopefully this will give a better idea of where things might be going wrong:

THIS WORKS

protected void UpdateButton(object sender, EventArgs e)
{
var masterPage = this.Page.Master;
var updatePanel = masterPage.FindControl("Panel2");

var div = (HtmlGenericControl)updatePanel.FindControl("updateThis");
div.Style.Add("color", "#ff0000");

UpdateButton.Text = "Done!";
}


I had #updateThis in the FindControl() method. Don't be like me!

Answer

You should add the runat="server" attribute to the div control, to make it visible in code-behind:

<div id="updateThis" runat="server"><p>Test text</p></div>

You can also remove Controls[0] in the event handler (but it works if you keep it, according to my tests):

protected void UpdateButton(object sender, EventArgs e) 
{
    var masterPage = this.Page.Master;
    var updatePanel = masterPage.FindControl("Panel2");

    var div = (HtmlGenericControl)updatePanel.FindControl("updateThis");
    div.Style.Add("color", "#ff0000");  
}
Comments