Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

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.