The provided method is for filling the data in dropdown list. First, the selected index of dropdown is
-1
but after
Databind()
method line, the selected index becomes
0
and first item of the list gets selected by default. I tried to set selected index to
-1
or
clearSelections
, but it's not being set.
If I try to add the first value like select at 0th index. The
select
item is getting inserted in 0th index, but then the selected index becoming 1 after adding data and again the first item of list is getting selected.
This is the ASP.NET dropdown:
<asp:DropDownList ID="cmbCountry" runat="server" CssClass=" custom-dropdown" AppendDataBoundItems="false" EnableViewState="False" AutoPostBack="true" ViewStateMode="Enabled"></asp:DropDownList>
Below is code behind:
protected void Fill_Country()
{
DataSet ds = new DataSet();
ds = FunctionClass.ExecuteStoredProcedure("Fill_CountryName");
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
int i =cmbCountry.SelectedIndex;
cmbCountry.DataSource = ds.Tables[0];
cmbCountry.DataTextField = "Country";
cmbCountry.DataValueField = "Id";
cmbCountry.DataBind();
cmbCountry.SelectedIndex = - 1;
}
else
{
cmbCountry.DataSource = null;
cmbCountry.DataBind();
}
}
}
What I have tried:
ListItem defaultItem = new ListItem("Select", ""); cmbCountry.Items.Insert(0, defaultItem);
I am calling this function on page load so I checked like this on
page_load
event:
if (!Page.IsPostBack) { Fill_Country(); }