0

I have the code as,

<asp:ListItem Value="Above 50" Text="Above 50"  Enabled='<%# (((string)(Eval("Gender"))).Contains("Male"))? true:false%>'></asp:ListItem>

the condition is,if the user is male,then the item 'Above 50' should enable in the dropdownList,else not. here, 'Gender' is nothing but a bound field.

the error showing is,

Databinding expressions are only supported on objects that have a DataBinding event. System.Web.UI.WebControls.ListItem does not have a DataBinding event.

what is wrong in the code?

user7415073
  • 290
  • 4
  • 22
  • Where does the DropDownList control located? Could you post the code of it's parent control? – Win Mar 15 '17 at 15:35
  • `Contains` returns a Bool, so `'<%# ((string)(Eval("Gender"))).Contains("Male")%>'` should be sufficient. Or `'<%# Eval("Gender").ToString().Contains("Male")%>'` – JP Hellemons Jul 26 '17 at 13:15

2 Answers2

1

The ListItem doesn't have any data binding events. Hence Eval() cannot be used here.

You need to call the DataBound Event on your Drop Down list and perform the check there.

something like this -

protected void MyDropDownList_DataBound(object sender, EventArgs e)
        {
            var ddl = sender as DropDownList;
            foreach (ListItem item in ddl.Items)
            {
                if (Gender == "Male")
                {
                    item.Attributes.Add("disabled", "disabled");
                }
            }
        }

Please note that enabled = false will remove the list item while disabled = disabled will only grey it out.

NoviceProgrammer
  • 3,347
  • 1
  • 22
  • 32
0

I believe you are approaching the problem in slightly the wrong way. This question, and the answers, seem to be exactly what you are looking for: How do I data bind Control.Enabled to !(field)?

In your case, you would bind to a function or value that checks the Gender value.

Community
  • 1
  • 1
user3685427
  • 211
  • 2
  • 8