Search code examples
c#visual-studio-2012drop-down-menupageload

How to select a month in drop down list according current month upon page load?


I would like to write the code such that when I run my program, the Month Drop Down List is automatically selected according to date.time.now. month when I load the page.

I have tried the code below but I get an error saying:

" Cannot have multiple items selected in a Drop Down List".

I am unsure of what this means since I have no other items selected.

(My Month drop down list currently has list items from Jan to Dec denoted with the index 0-11)

int month = DateTime.Now.Month;

        for (int i = 0; i < MonthDropDownList.Items.Count; i++)
        {
            if (month == 1) //Jan
            {
                MonthDropDownList.Items[0].Selected = true;
            }
            else if (month == 2) //Feb
            {
                MonthDropDownList.Items[1].Selected = true;
            }
            else if (month == 3) //March
            {
                MonthDropDownList.Items[2].Selected = true;
            }
            else if (month == 4) //April
            {
                MonthDropDownList.Items[3].Selected = true;
            }
            else if (month == 5) //May
            {
                MonthDropDownList.Items[4].Selected = true;
            }
            else if (month == 6) //June
            {
                MonthDropDownList.Items[5].Selected = true;

            }
            else if (month == 7) //July
            {
                MonthDropDownList.Items[6].Selected = true;
            }
            else if (month == 8) //Aug
            {
                MonthDropDownList.Items[7].Selected = true;
            }
            else if (month == 9) //Sept
            {
                MonthDropDownList.Items[8].Selected = true;
            }
            else if (month == 10) //Oct
            {
                MonthDropDownList.Items[9].Selected = true;
            }
            else if (month == 11) //Nov
            {
                MonthDropDownList.Items[10].Selected = true;
            }
            else if (month == 12) //Dec
            {
                MonthDropDownList.Items[11].Selected = true;
            }

        }

What do I have to change in my code to solve this issue? Or is there another solution I can use to automatically select the current month?


Solution

  • You can simply do like this

     MonthDropDownList.SelectedIndex = month - 1;