如何防止DropDownList中的重复值?

时间:2014-05-26 10:30:20

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

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

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

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

3 个答案:

答案 0 :(得分:1)

您可以通过一种方式申请您的问题。 在Binding完成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;
      }
    }
  }
}

谢谢......

答案 1 :(得分:0)

if(!DropDownList1.Items.Contains(DropDownList1.SelectedItem))
    {
        DropDownList1.Items.Add(DropDownList1.SelectedItem);
    }

答案 2 :(得分:0)

您可以使用 FindByValue FindByText 来匹配所选值或下拉列表中的所选项

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

if(!DropDownList1.Items.FindByText(DropDownList1.SelectedItem.Text))
    {
        DropDownList1.Items.Add(DropDownList1.SelectedValue);
    }
相关问题