Dynamically enable asp button based on datasource value
-
30-09-2019 - |
Question
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") %>'
OTHER TIPS
This is the code that worked!
Enabled='<%# Eval("wrqst_need_ind").ToString().Equals("Y".ToString()) ? Convert.ToBoolean(1) : Convert.ToBoolean(0) %>'
I'm not sure about all the "Convert.ToBoolean(1)" stuff you've got going on. If you want true and false just write true and false (without quotes or it will be treated as a string).
eg. Enabled='<%#Eval("wrqst_need_ind") == "Y" ? true:false %>'
Of course as I type that it occurs to me that you don't need to use this kind of operator. the condition returns true or false anyway so the above simplifies to:
Enabled='<%#Eval("wrqst_need_ind") == "Y" %>'
I'm pretty sure the correct keywork is "if" in lowercase.
In case it will help anyone else...
This style did not work for me:
(Eval("status").ToString()).Equals("Done")
but this style did work:
(Eval("status").ToString()).Contains("Done")