Search code examples
asp.netdrop-down-menulist.selectedvalue

How to show selected index on top in DropDownList?


Actually i am displaying months in first list on selecting the month if the value of month is other than 31 it shows at top otherwise it shows jan at top how to show the other one?

Here is code:

Code behind:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList2.Items.Clear();
    for (int i = 1; i <= int.Parse(DropDownList1.SelectedValue); i++)
    {
        DropDownList2.Items.Add(new ListItem("" + i));
    }
}

Designer source:

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem Value="31">Jan</asp:ListItem>
    <asp:ListItem Value="29">Feb</asp:ListItem>
    <asp:ListItem Value="31">Mar</asp:ListItem>
    <asp:ListItem Value="30">April</asp:ListItem>
    <asp:ListItem Value="31">May</asp:ListItem>
    <asp:ListItem Value="30">June</asp:ListItem>
    <asp:ListItem Value="31">July</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>

Problem is:

If i select march or may or any item with value 31 jan is shown at to while in other case the selected one is shown.


Solution

  • Values of ListItems should be unique.

    Default selected item is Jan (value = 31), so everything will work fine when you click on items with another values (29 and 30).

    When you click on Mar, May, July (value = 31), then Jan becomes selected.

    To achieve the behavior you want, use another approach.


    The best solution is:

    using System.Linq;
    
    int count =  DateTime.DaysInMonth(
         DateTime.Today.Year,
         int.Parse(DropDownList2.SelectedIndex + 1)); // sic!
    
    DropDownList2.Items.AddRange(
        Enumerable.Range(1, count)
            .Select(i => new ListItem(i.ToString()))
            .ToArray());
    

    So you don't need to hard-code anything! Everything is already in .NET FCL. Just determine month's number from it's index into the list.