Reputation: 2495
I have a dropwdown list with few items like this(in the format "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".
Now I have to remove the third item(Peter Heins - 5456454) from the dropdownlist which matches with the number my query returns.
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.
Upvotes: 1
Views: 1523
Reputation: 125
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 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);
}
}
Upvotes: 1
Reputation: 5106
You could do something like this:
var removeItem = ddl.Items.Cast<ListItem>()
.Where(x => x.Value.Contains(number))
.FirstOrDefault()
ddl.Items.Remove(removeItem);
Upvotes: 2