ASP.Net: System.NullReferenceException: Object reference not set to an instance of an object

Last Reply on Jan 09, 2018 05:20 AM By dharmendr

Posted on Jan 09, 2018 05:04 AM

Dear All,

I have checkbox list binding from code behind with the years 

 <asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatDirection="Horizontal"></asp:CheckBoxList>
protected void Page_Load(object sender, EventArgs e)
{
    CheckBoxList1.Items.Clear();
    var currentYear = DateTime.Today.Year;
    for (int i = 4; i >= 0; i--)
    {
        // Now just add an entry that's the current year minus the counter
        CheckBoxList1.Items.Add((currentYear - i).ToString());
    }
}

 here i am getting the error

An exception of type 'System.NullReferenceException' occurred in KPI.dll but was not handled in user code

Object reference not set to an instance of an object.

protected void Button1_Click(object sender, EventArgs e)
{
    string yearly = CheckBoxList1.SelectedItem.ToString();
    Response.Redirect("~/InsertDatatoKPI.aspx?userID=" + yearly);
}

Thanks

Posted on Jan 09, 2018 05:20 AM Modified on on Jan 09, 2018 06:10 AM

Hi irshad1231,

Write the CheckBox bind code inside !IspostBack condition.

Check this example. Now please take its reference and correct your code.

HTML

<asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatDirection="Horizontal">
</asp:CheckBoxList>
<asp:Button Text="Send" runat="server" OnClick="Button1_Click" />

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        CheckBoxList1.Items.Clear();
        var currentYear = DateTime.Today.Year;
        for (int i = 4; i >= 0; i--)
        {
            // Now just add an entry that's the current year minus the counter
            CheckBoxList1.Items.Add((currentYear - i).ToString());
        }
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    string yearly = "";
    for (int i = 0; i < CheckBoxList1.Items.Count; i++)
    {
        if (CheckBoxList1.Items[i].Selected)
        {
            yearly += CheckBoxList1.Items[i].Text + ",";
        }
    }
    Response.Redirect("~/InsertDatatoKPI.aspx?userID=" + yearly.Substring(0, yearly.Length - 1));
}

LandingPage

protected void Page_Load(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(Request.QueryString["userID"]))
    {
        Response.Write(Request.QueryString["userID"]);
    }
}

Screenshot