ASP.NET - 如何从列表框中删除重复项

时间:2016-05-26 07:30:22

标签: c# asp.net listbox duplicates

我想,在ListItem中添加一个字段以从ListBox中删除重复项;

   I want here the code where removes duplicates...

这是我在SPList中添加元素的代码;

foreach (ListItem listItem in _lboxRight.Items)
{
   sb.Append(listItem + "; ");
}

sb.Remove(sb.Length - 2, 1);

item["Project"] = sb;

1 个答案:

答案 0 :(得分:0)

您应该在向ListBox添加项目之前检查重复项

  protected void Page_Load(object sender, EventArgs e)
    {
        BindData();
    }

    private void BindData()
    {
        List<string> values = ViewState["Colours"] as List<string>;

        if (values == null)
        {
            values = new List<string>
            {
                "red",
                "green",
                "blue"
            };
        }

        ViewState["Colours"] = values;

        colours.DataSource = values;
        colours.DataBind();
    }

    protected void btnAddToListBox_Click(object sender, EventArgs e)
    {
        List<string> values = ViewState["Colours"] as List<string>;
        string newColour = txtNewColour.Text;
        bool exists = false;

        values.ForEach(i =>
            {
                if (i == newColour)
                    exists = true;
            });

        if(!exists)
        {
            values.Add(txtNewColour.Text);
            this.DataBind();
        }
    }