【问题标题】:How to Prevent duplicate values in DropDownList?如何防止 DropDownList 中的重复值?
【发布时间】:2014-05-26 10:30:19
【问题描述】:

我有一个 DropDownList,其中的值来自不同的表。我想阻止在 DropDownList 中输入值,如果它已经具有相同的值。我尝试了以下代码,但它不起作用。

if(!DropDownList1.Items.Contains(new ListItem(DropDownList1.SelectedValue)))
    {
        DropDownList1.Items.Add(DropDownList1.SelectedValue);
    }

我在页面加载事件中执行的上述代码但无济于事。 任何帮助将不胜感激。

【问题讨论】:

  • 尝试从不同的表中获取unique 值,这会阻止这种条件检查。
  • 投反对票的原因是什么?
  • 我还没有投票。我看不出有任何理由downvote

标签: c# asp.net .net c#-4.0 listbox


【解决方案1】:

您可以通过一种方式申请您的问题。 绑定完成后,您的 DropDownList 使用以下方法。

    DropDownList1.Items.Add(DropDownList1.SelectedValue);

使用以下方法,如...

    RemoveDuplicateItems(DropDownList1);       


    void RemoveDuplicateItems(DropDownList ddl)
{
  for (int i = 0; i < ddl.Items.Count; i++)
  {
    ddl.SelectedIndex = i;
    string str = ddl.SelectedItem.ToString();
    for (int counter = i + 1; counter < ddl.Items.Count; counter++)
    {
      ddl.SelectedIndex = counter;
      string compareStr = ddl.SelectedItem.ToString();
      if (str == compareStr)
      {
        ddl.Items.RemoveAt(counter);
        counter = counter - 1;
      }
    }
  }
}

谢谢...

【讨论】:

    【解决方案2】:
    if(!DropDownList1.Items.Contains(DropDownList1.SelectedItem))
        {
            DropDownList1.Items.Add(DropDownList1.SelectedItem);
        }
    

    【讨论】:

      【解决方案3】:

      您可以使用 FindByValueFindByText 来匹配下拉列表中的选定值或选定项

      if(!DropDownList1.Items.FindByValue(DropDownList1.SelectedValue))
          {
              DropDownList1.Items.Add(DropDownList1.SelectedValue);
          }
      
      if(!DropDownList1.Items.FindByText(DropDownList1.SelectedItem.Text))
          {
              DropDownList1.Items.Add(DropDownList1.SelectedValue);
          }
      

      【讨论】:

        猜你喜欢
        • 2020-03-07
        • 1970-01-01
        • 2017-12-25
        • 1970-01-01
        • 1970-01-01
        • 2011-10-28
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        相关资源
        最近更新 更多