Dragan
Dragan

Reputation: 3743

Dropdownlist asp.net not working properly

I have the following mark-up:

<asp:DropDownList ID="ddlTownships" DataTextField="Name" AutoPostBack="True" AppendDataBoundItems="True" DataValueField="Id" runat="server" OnSelectedIndexChanged="ddlTownships_SelectedIndexChanged">
                        <asp:ListItem Value="0" Text="Please select a township"></asp:ListItem>
                    </asp:DropDownList>

and this is the code behind:

protected void ddlRegions_SelectedIndexChanged(object sender, EventArgs e)
        {
            var townshipDAO = (TownshipDAO)FactoryDAO.getInstance().getDAOByType(DAOEnum.Township);
            ddlTownships.DataSource = townshipDAO.getAllTownshipsByRegionId(Int64.Parse(ddlRegions.SelectedValue));
            ddlTownships.DataBind();
            liTownships.Visible = true;
            liSettlements.Visible = false;
            divPhasesConsole.Visible = false;
            liNumberOfStands.Visible = false;
            divFirstDelimiter.Visible = false;
        }

Basically whenever a user selects an item from the ddlRegion, I get all townships with the regionId selected and repopulate the dropdownlist. However the ddlTownships remembers the previously selected townships with different regions. Note that I have the property AppendDataBoundItems="True" because that was the only way I could add a list item that says "Please select a township". How can I leave the listitem defined in the mark-up and prevent the previous items from showing up after the ddl is repopulated.

Thanks for your time.

Upvotes: 1

Views: 1451

Answers (1)

MikeSmithDev
MikeSmithDev

Reputation: 15797

You can insert a new list item at a particular index from the code behind. So you could remove AppendDataBoundItems and add this after the databinding:

ddlTownships.Items.Insert(0, new ListItem() { Text = "Please select a township", Value = "0" });

Another helpful thing to know is that can clear out the list before databinding:

ddlTownships.Items.Clear();

Upvotes: 1

Related Questions