Hi there,
I was following this tutorial.
It all worked, but if I add some SelectedIndexChanged method in drop down list ddlMonths , it doesn't work.
And the error says
NullReferenceException: Object reference not set to an instance of an object.
This is my code
<asp:DropDownList ID="ddlMonths" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="ddlMonths_SelectedIndexChanged">
<asp:ListItem Text="Select" Value=""></asp:ListItem>
<asp:ListItem Text="JAN" Value="1"></asp:ListItem>
<asp:ListItem Text="FEB" Value="2"></asp:ListItem>
<asp:ListItem Text="MAR" Value="3"></asp:ListItem>
<asp:ListItem Text="APR" Value="4"></asp:ListItem>
<asp:ListItem Text="MAY" Value="5"></asp:ListItem>
<asp:ListItem Text="JUN" Value="6"></asp:ListItem>
<asp:ListItem Text="JUL" Value="7"></asp:ListItem>
<asp:ListItem Text="AUG" Value="8"></asp:ListItem>
<asp:ListItem Text="SEP" Value="9"></asp:ListItem>
<asp:ListItem Text="OCT" Value="10"></asp:ListItem>
<asp:ListItem Text="NOV" Value="11"></asp:ListItem>
<asp:ListItem Text="DEC" Value="12"></asp:ListItem>
</asp:DropDownList>
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DateTime dateTime = DateTime.Now;
// List of Months to be display.
List<ListItem> months = new List<ListItem>();
for (int i = 1; i <= 8; i++)
{
months.Add(ddlMonths.Items.Cast<ListItem>()
.Where(x => x.Value.Equals(dateTime.AddMonths(-i).Month.ToString()))
.FirstOrDefault());
}
//Determines first item i.e.Equals Default Item.
ListItem defaultItem = ddlMonths.Items[0];
//Clears all items in the DropDownList.
ddlMonths.Items.Clear();
//Reverse the List of last two months.
months.Reverse();
//Inserts Default Item.
months.Insert(0, defaultItem);
//Assigning month to DropDownList.
ddlMonths.DataSource = months;
ddlMonths.DataBind();
}
protected void ddlMonths_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write(ddlMonths.SelectedIndex);
}
}