Adding and Removing Items from DropDownList - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Adding and Removing Items from DropDownList

shinsnakeshinsnake Posts: 93Member
[b][red]This message was edited by shinsnake at 2006-9-1 9:44:34[/red][/b][hr]
I'm adding items to a dropdownlist based on whether or not an XML file has multiple elements in it. When it has more than one element, I add each element's inner text to the drop down list. The problem occurs when I need to use the dropdownlist again, it already has the items in it, but it adds the items again. For instance, if I had 2 Items, Columbus, OH and Columbus, GA, and then I used the ddl again, I would have Columbus, OH, Columbus, GA, Columbus, OH and Columbus, GA as selectable items. So my thought would be that when I don't use the ddl, to remove all of the items. Here's the code I came up with:

[code]foreach (XmlElement xelLocCode in xnlistLocCode)
{
if (xnlistLocCode.Count == 1)
{
strLocCode = xelLocCode.GetAttribute("id");
ddlLocation.Visible = false;
}
else
{
string testItem = xelLocCode.InnerText.ToString();
if (!ddlLocation.Items.Contains(xelLocCode.InnerText.ToString()))
{
ddlLocation.Items.Add(xelLocCode.InnerText.ToString());
ddlLocation.Visible = true;
}
}
}[/code]

So I planned to add a [code]ddlLocation.Items.Remove()[/code] statement in the if statement, but you have to remove based on string or listitem. To do that, I'd have to re-read the XML again, which isn't a hard thing to do, I just know it's redundant.

Is there anyway to unload all items in a dropdownlist before adding new ones?

The other thing I was attempting, as you can see with the second If statement, was to see if the item existed in the ddl before I added it. I tried contains, but you can't use a string as a list item. It gives me a compiler error.

Comments

  • shinsnakeshinsnake Posts: 93Member
    Never mind, figured it out:

    [code]foreach (XmlElement xelLocCode in xnlistLocCode)
    {
    if (xnlistLocCode.Count == 1)
    {
    strLocCode = xelLocCode.GetAttribute("id");
    ddlLocation.Visible = false;
    }
    else
    {
    ListItem li = new ListItem(xelLocCode.InnerText.ToString());
    if (!ddlLocation.Items.Contains(li))
    {
    ddlLocation.Items.Add(xelLocCode.InnerText.ToString());
    ddlLocation.Visible = true;
    }
    }
    }[/code]
Sign In or Register to comment.