0

我想禁用ItemList. 我尝试了以下代码的变体,但似乎没有任何效果。我希望让残疾人Items留在 中list,但要灰掉。我在这个主题上似乎有类似的帖子,但似乎没有任何效果。

List<SelectListItem> selectitem = new List<SelectListItem>();

selectitem.Add(new SelectListItem { Text = "Select", Value = "-1", Disabled = false });

while (reader.Read())
{
string displayText = "TextTest";
string displayValue = "ValueTest";

selectitem.Add(new SelectListItem { Text = displayText, Value = displayValue, Disabled = true });
}

EstimateDropDownList.DataSource = selectitem;
EstimateDropDownList.DataTextField = "Text";
EstimateDropDownList.DataValueField = "Value";
EstimateDropDownList.DataBind();

...

  internal class SelectListItem
    {
        public string Text { get; set; }
        public string Value { get; set; }
        public bool Disabled { get; set; }
    }

...

<asp:DropDownList ID="EstimateDropDownList" runat="server" Width="200px" Height="27px"
    AutoPostBack="true" OnSelectedIndexChanged="EstimateDropDownList_SelectedIndexChanged">
</asp:DropDownList>

我也试过这个,但这也不起作用。

EstimateDropDownList.DataSource = selectitem;

foreach (ListItem item in EstimateDropDownList.Items)
   {
     if (true)
      {
          item.Attributes.Add("disabled", "disabled");
      }
   }

EstimateDropDownList.DataTextField = "Text";
EstimateDropDownList.DataValueField = "Value";
EstimateDropDownList.DataBind();
4

2 回答 2

0

下拉菜单是带有“选项”元素的“选择”控件。在大多数浏览器中,您只能禁用(或着色)控件本身,而不是特定的“选项”。在过去,这有点不同。如果你确实想这样做,有许多现成的 JS Dropdown 控件甚至引导程序可以很好地做到这一点。

于 2019-03-18T08:38:47.090 回答
0

看来我错了。有一个选项可以禁用 HTML 中的特定选择选项项。见这里:https ://www.w3schools.com/tags/tag_option.asp

例如,请参阅此下拉列表:

<select>
  <option value="volvo">Volvo</option>
  <option value="saab" disabled>Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

要利用这个:

ListItemCollection lic = new ListItemCollection();
lic.Add(new ListItem("first", "1"));
lic.Add(new ListItem("second", "2", false));
lic.Add(new ListItem("third", "3"));

foreach(ListItem li in lic)
{
    //create a new list item, because otherwise it will skip disabled items.
    ddl.Items.Add(new ListItem(li.Text, li.Value));
    if(li.Enabled == false)
    {
        ddl.Items[ddl.Items.Count - 1].Attributes.Add("disabled", "");
    }
}

这是一个相当奇怪的解决方法,因为 asp.net 控件一开始就应该知道如何生成 disabled 属性。我不知道为什么会这样,但可能有一个正当的理由。我肯定会以不同的方式做到这一点,或者通过使用文本,检查回发,或者只是忽略禁用的选项。显然,它不应该是这样的。

于 2019-03-19T07:56:00.667 回答