简体   繁体   中英

Enabling List item of DropdownList in c# asp.net

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM