Question

I'd like to set a button's enabled state to be the negation of a value.

So given this code:

<asp:CheckBox ID="DefaultChecked" 
              Checked='<%# Bind("IsDefaultMessage") %>' 
              Enabled="false" 
              runat="server" />

<asp:LinkButton ID="MakeDefaultButton" 
                runat="server" 
                CommandName="MakeDefault' 
                CommandArgument='<%# Bind("ResidentialInfoID") %>' 
                Text="Make Default" />

How can I make the LinkButton Enabled attribute false if IsDefaultMessage == true?

Was it helpful?

Solution

Use Eval instead of Bind. Bind is for two-way binding, i.e. for cases where you need to be able to save the data back to your data source.

When you use Bind, the compiled page will actually have generated code that uses Eval to set the value, plus some code to read out the value for saving. Because Bind is replaced with generated code, you can't use any extra logic with Bind.

<asp:CheckBox ID="DefaultChecked" Checked='<%# !(bool)Eval("IsDefaultMessage") %>' Enabled="false" runat="server" />
<asp:LinkButton ID="MakeDefaultButton" runat="server" CommandName="MakeDefault' CommandArgument='<%#Bind("ResidentialInfoID") %>' Text="Make Default"/>

OTHER TIPS

If you can use Eval, it is just a method of the Control class. It's only special in that it needs to be in the context of a data bound block <%# ... %>. Other than that, you can basically treat the block like a regular <%= %> expression block:

<%# !(bool)Eval("IsDefaultMessage") %>

If you want to still Bind it (Eval isn't round-trip), than you'll need to negate it back and forth during databinding. You may not need to do this though, if you can just re-word the control. For example, if a check box, instead of labelling it "Is Not Default Message" to the user and negating it back and forth, than lable it "Is Default Message". Contrived example, but you get the idea.

I've never used Bind but my understanding is that it is similar to Databinder.Eval. Either way, both methods return objects so you need to cast it to a boolean before evaluating it.

<%# !Convert.ToBoolean(Bind("IsDefaultMessage") %>

Edit: Looks like this can't be done and using a SqlDataSource on the page would solve the problem. http://forums.asp.net/t/1009497.aspx.

In case someone is looking for an option with VB.Net

<asp:CheckBox ID="DefaultChecked" Checked='<%# NOT (Eval("IsDefaultMessage")) %>' Enabled="false" runat="server" />

As I recall (It's been a while), there's no particular magic in <%#Bind(. It's just #Bind( inside <%....%>. Which means you'd want:

 <%  ! #Bind("IsDefaultMessage") %>'

The code

Checked='<%# Eval("IsDefaultMessage").ToString().Length() > 4 %>'

will return true if IsDefaultMessage is false Since "False".Length = 5 and "True".Length = 4

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top