tags:

views:

323

answers:

3

Hi,

One of my code behind file is sending some boolean value (read from the data base) to the corresponding.aspx file. I want to change the css style class of the container division based on this boolean value. I tried to do it the following way,

code behind file:

protected void Page_Load(object sender, EventArgs e)
{
    Result.InnerText = "false";  //In real scenario, this is retrieved from a db
}

aspx file:

<form id="form1" runat="server">
<% if (Result.InnerText == "true") { Result.Style["Color"] = "#000000"; } else { Result.Style["Color"] = "#ff0000"; } %>
<div id="Result" runat="server">
</div>
</form>

Its seems to be working properly, but I am not satisfied with this snippet. Is this the way to do it?? I am doing it properly ???

UPDATE:

Are there any other way to do this ? If so which is the better one ? Note: I must be able to change the css class name (applied to the division) whenever required

+2  A: 

You could set the color in c# (code behind) after the line, where you get the variable value from the DB.

Result.Style["Color"] = (myDBVariable == "false") ? "#000000" : "#ff0000";
shahkalpesh
I don't wanna control the styles from code behind files
sudarsanyes
why? any particular reason? If you write c# code (either in code-behind or inline with aspx page), it will become 1 class file.
shahkalpesh
Its a presentation logic, isn't it ? so i want to have it separated out from the business logic file
sudarsanyes
It is a presentation thing. But, you are writing code inside an asp.net page (which has page load, init event). Isn't that part of presentation already?
shahkalpesh
Yep. So can you give me a neat solution for this problem ? My objective is simple, if the value is true, i want some css class to be added to that tag, else some other css class. It needn't be like the snippet I had mentioned above.
sudarsanyes
shahkalpesh
+3  A: 

Your Result Div is wired up in the codebehind so you don't need to put the if statement in the ASPX at all.

protected void Page_Load(object sender, EventArgs e)
{
    Result.InnerText = "false";  //In real scenario, this is retrieved from a db

    if (Result.InnerText == "true") {
        Result.Style["Color"] = "#000000";
    } else {
        Result.Style["Color"] = "#ff0000";
    }
}
CptSkippy
I don't wanna control the styles from the code behind files
sudarsanyes
+2  A: 

First I would create a public variable, say result. Then in your .aspx do this:

<div id="result" class='<%=(result?"someClass":"someOtherClass") %>'>
    Your text
</div>

Or if you want to do it all on the backend (.aspx):

<div id="result" runat="server">
    Your text
</div>

.cs

if (result) {
    result.CssClass = "yourClass";
} else {
    result.CssClass = "anotherClass";
}
Jason
can you explain on this a bit more ?
sudarsanyes
c# doesn't have an "iif". I think it should be this...result ?"someClass":"someOtherClass"
herbrandson
oh... well vb does :P... updated...
Jason