Search code examples
asp.netgridviewdynamicbuttontemplatefield

Dynamically enable asp button based on datasource value


SOLVED: See my solution below!

using aspx with C# code behind.

I have the following code in a button in a item template in a gridview:

Enabled='<%# IIF(Eval("wrqst_need_ind") == "Y","TRUE","FALSE") %>'

I am getting the following error:

The name 'IIF' does not exist in the current context

What am I doing wrong? I get the same error if I use "IF" rather than "IIF"

The full item template code is as follows:

<ItemTemplate>
                <asp:Button  ID="wrqst_need_ind_btn" runat="server" Text = "Create WR" 
                    onClientClick="javascript:popUp('popup_createWR.aspx')"  
                    Enabled='<%# IIF(Eval("wrqst_need_ind") == "Y","TRUE","FALSE") %>'
                    CommandArgument='<%# Eval("dvc_nm") + "|" + Eval("data_orgtn_yr") %>'/>
</ItemTemplate>

If I take the line out it works fine.

Seems to me like this should work...

EDIT: I am now using this:

Enabled='<%#Eval("wrqst_need_ind") == "Y" ? "TRUE" : "FALSE" %>'

And geting this error:

The server tag is not well formed.

Thanks so much for your help!

Update:

I tried this:

Enabled='<%# Eval("wrqst_need_ind") == "Y" ? Convert.ToBoolean(1) : Convert.ToBoolean(0) %>' and it ran!

But, every button was disabled. So I tried:

Enabled='<%# Eval("wrqst_need_ind") == "Y" ? Convert.ToBoolean(1) : Convert.ToBoolean(1) %>'

and then every button was disabled. It seems that every time it is returning false... why?

SOLVED: See my solution below!


Solution

  • In C#, that ternary syntax is:

    Eval("wrqst_need_ind") == "Y" ? "TRUE" : "FALSE"
    

    If you happen to be using VB.NET (it looks like you are not), use the If function.

    If(Eval("wrqst_need_ind") == "Y", "TRUE", "FALSE")
    

    EDIT: It turns out that == here will not compare the string contents, but the string objects. So, instead, you must use .Equals("Y"). So, community-generated final answer is:

    Enabled='<%# Eval("wrqst_need_ind").Equals("Y") %>'