Click here to Skip to main content
15,851,090 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
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.NET
<asp:DropDownList ID="cmbCountry" runat="server" CssClass=" custom-dropdown" AppendDataBoundItems="false" EnableViewState="False" AutoPostBack="true" ViewStateMode="Enabled"></asp:DropDownList>

Below is code behind:
C#
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:

C#
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:
C#
if (!Page.IsPostBack) { Fill_Country(); }
Posted
Updated 27-Oct-23 8:13am
v6
Comments
ashwini gaikwad 2021 26-Oct-23 1:19am    
Please help me to resolve my issue

1 solution

A DropDownList renders as a <select size="1"> HTML element.

<select>: The HTML Select element - HTML: HyperText Markup Language | MDN[^]

That element (with a size of 1) does not support a "no option selected" state; if none of the rendered <option> elements have the selected attribute, then the first option is always selected.

The typical solution is to insert a dummy option at the start of the list to represent the "no option selected" state. Which you have already done in the first code block under "what I have tried". But you didn't explain what the problem was with that code.
 
Share this answer
 
Comments
ashwini gaikwad 2021 26-Oct-23 7:50am    
Thank you for your response i found the solution

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900