Vaibhav Yadav
Vaibhav Yadav

Reputation: 1

Items in dropdownlist is lost , only one item is coming in dropdown list in asp.net after page is refreshed

I have a dropdown on the page in asp.net, which contains list of countries. When the page is loaded, I have bound the datatable to dropdown list. On page load, all the countries list is populated in the dropdown list. Then, once I refresh the page, only India is populated in the dropdown list.Can anyone help me with the issue? Thanks in advance.

Here is the code : Design :

<asp:DropDownList ID="ddlCountry" runat="server" TabIndex="7" 
  placeholder="by Country" AutoPostBack="true" 
 OnSelectedIndexChanged = "ddlCountry_SelectedIndexChanged">
</asp:DropDownList>

Code Behind :

DataSet CountryMasters =Global.DsCountry;//(DataSet)Application["CountryMasters"];
DataTable dtcountry = CountryMasters.Tables[0];
ddlcountry.Items.Clear();

ddlcountry.DataSource = dtcountry;

ddlcountry.DataTextField = "CountryName";
ddlcountry.DataValueField = "CountryCode";
ddlcountry.DataBind();
ddlcountry.Items.Insert(0, new ListItem("Select", ""));

Upvotes: 0

Views: 116

Answers (1)

Paul Alan Taylor
Paul Alan Taylor

Reputation: 10680

Try wrapping your initialisation code with a conditional that checks if the form is being posted back.

if (!this.IsPostBack)
{
    DataSet CountryMasters =Global.DsCountry;//(DataSet)Application["CountryMasters"];
    DataTable dtcountry = CountryMasters.Tables[0];
    ddlcountry.Items.Clear();

    ddlcountry.DataSource = dtcountry;

    ddlcountry.DataTextField = "CountryName";
    ddlcountry.DataValueField = "CountryCode";
    ddlcountry.DataBind();
    ddlcountry.Items.Insert(0, new ListItem("Select", ""));
}

Upvotes: 0

Related Questions