简体   繁体   English

在c#asp.net中启用DropdownList的列表项

[英]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. 条件是,如果用户是男性,则应该在下拉列表中启用“ 50岁以上”项目,否则不启用。 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)? 这个问题和答案似乎正是您要寻找的: 如何将Control.Enabled数据绑定到!(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. ListItem没有任何数据绑定事件。 Hence Eval() cannot be used here. 因此, Eval()不能在这里使用。

You need to call the DataBound Event on your Drop Down list and perform the check there. 您需要在下拉列表中调用DataBound事件并在那里进行检查。

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. 请注意, enabled = false将删除列表项,而disabled = disabled只会将其变灰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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