I am trying to extract month and year from database and show it as selected in the dropdown. Ex: Month and year, consider 2 and 2013. I want the dropdown expmonth to show Febraury and expyear as 2013 when the page is loaded.
When i tried the below code, it did not show me 2 and 2013 instead showed Jan and 2010 which is default. Where do you think i am doing wrong, guys??
<asp:DropDownList ID="ddExpMonth" runat="server" TabIndex="19" Width="80px" CausesValidation="True">
</asp:DropDownList>
<asp:DropDownList ID="ddExpYear" runat="server" TabIndex="20" Width="57px" CausesValidation="True">
</asp:DropDownList>
LoadExpDateInfo();
ddExpMonth.SelectedIndex = expmonth-1;
ddExpMonth.SelectedItem.Value = expmonth.ToString();
ddExpYear.SelectedIndex = expyear;
int currentyear = Convert.ToInt16(DateTime.Now.Year);
int diff = expyear - currentyear;
ddExpYear.SelectedItem.Value = diff.ToString();
expyear and expmonth values are retrieved from database.
private void LoadExpDateInfo()
{
string[] arrMonths = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
ListItem item;
for (int i = 0; i < 12; i++)
{
item = new ListItem();
item.Text = arrMonths[i];
item.Value = Convert.ToString(i + 1);
ddExpMonth.Items.Add(item);
}
for (int i = -1; i < 10; i++)
{
item = new ListItem();
item.Text = Convert.ToString(System.DateTime.Now.AddYears(1).AddYears(i).Year);
item.Value = Convert.ToString(System.DateTime.Now.AddYears(1).AddYears(i).Year);
ddExpYear.Items.Add(item);
}
}
Thanks for all your help guys. I appreciate your time 🙂
You should only have to set the selected index, not the value of the selected item. The following should work, although I’d expect your initial code to have some effect as well. Are you setting the selected index early enough in the page lifecycle? You can test this by just setting the selected index to a constant value (i.e. 3) and see if it defaults to April.