1

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.

1
  • Do You insert any times into those DropDownList in Page_Init or Page_Load events? In order to make this code to work, you shouldn't add items in ddlRegions_SelectedIndexChanged, but rather check for a selected item in Page_Init and repopulate the second list based on it. Commented Dec 9, 2012 at 17:40

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

yea i figured out the insert() method in the meantime. However your answer is correct. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.