简体   繁体   English

如何从c#中的dropdownlist控件中删除项目

[英]How to remove an item from dropdownlist control in c#

I have a dropwdown list with few items like this(in the format "name-number"): 我有一个下拉列表,其中包含很少这样的项目(格式为“name-number”):

     George Michael - 456456
     Justin Dukes - 5644654
     Peter Heins - 5456454
     Mark Twain - 4454564

Now i have to delete an item from the above list based on the value i have from other query. 现在我必须根据我从其他查询中获得的值从上面的列表中删除一个项目。

My other query gives me a number in string format and i have to remove exactly the same item which is in the above dropdownlist second part(after hyphen). 我的另一个查询给了我一个字符串格式的数字,我必须删除完全相同的项目,在上面的下拉列表第二部分(连字符后)。

For ex: My query gives me "5456454". 例如:我的查询给了我“5456454”。

Now I have to remove the third item(Peter Heins - 5456454) from the dropdownlist which matches with the number my query returns. 现在我必须从下拉列表中删除第三项(Peter Heins - 5456454),该项与我的查询返回的数字相匹配。

I am trying to use 我正在尝试使用

ddl.Items.Remove

But Im not getting what parameter i should pass. 但我没有得到我应该通过的参数。 Both the text and value fields are same in the dropdownlist and i cannot modify that. 文本和值字段在下拉列表中都是相同的,我无法修改它。 So i cannot use 所以我不能用

ddl.Items.FindByValue()

Any help? 有帮助吗?

Thanks in advance. 提前致谢。

You could do something like this: 你可以这样做:

var removeItem = ddl.Items.Cast<ListItem>()
                          .Where(x => x.Value.Contains(number))
                          .FirstOrDefault()

ddl.Items.Remove(removeItem);

If you're populating your DropDownList with ListItem objects, I would set the text for example to "Peter Heins - 5456454" and the value to "5456454". 如果您使用ListItem对象填充DropDownList,我会将文本设置为“Peter Heins - 5456454”,值为“5456454”。

     ListItem exampleItem = new ListItem("Peter Heins - 5456454", "5456454"); 

Then, you could do as you described and call 然后,你可以像你描述的那样做并打电话

     string value = "5456454";
     ListItem valueToRemove = ddl.Items.FindByValue(valueToRemove);
     dd1.Remove(valuetoRemove);

edit: If you absolutely cannot change the value (whether it be for school purposes or some other reason) I would do something like this. 编辑:如果你绝对无法改变价值(无论是出于学校目的还是其他原因),我会做这样的事情。

        string id = "5456454";
        foreach (ListItem item in dd1.Items)
        {
            if (item.Text.Contains(id))
            {
                dd1.Items.Remove(item);
            }
        }

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

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