0

I am trying to store the cookie in an array of string and splitting it .when i try to display the array i am getting index out of bound error in the for loop.

Please not the the value of "cboColumn.getSelectedValues()" is a list of selected columns from a grid which is in format"column1,column2,column3......columnn"

Response.Cookies["Column"].Value = cboColumn.getSelectedValues();
    String items = Request.Cookies["Column"].Value;
    String[] item = items.Split(',');
    Response.Write(items);
    Response.Write(item[0]);
    for (int i = 0; i <= item.Length; i++)
    {
        Response.Write(item[i]);
    }

1 Answers1

0

Change your for loop like this:-

for (int i = 0; i <= item.Length - 1; i++)
{
   Response.Write(item[i]);
}

Or as suggested by @BillK, you can simply change the condition like this:-

for (int i = 0; i < item.Length ; i++)

Array is zero index based so it will range from 0 to (n-1) but you are trying to fetch value from 0 to n, which is causing this issue.

Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
  • Or, just change <= to = – BillK Mar 05 '15 at 05:15
  • @BillK - Yup thnx! Updated. – Rahul Singh Mar 05 '15 at 05:17
  • @Rahul Singh hi the answer worked .now i am trying to access the cookie in another function but getting "Object reference not set to an instance of an object" error. public void xyz() { String[] items = null; String itemss = Request.Cookies["Column"].Value; if(!itemss.Equals("")) items=itemss.Split(','); } protected void cboColumn_OkButtonClicked(object sender, EventArgs e) { Response.Cookies["Column"].Value = cboColumn.getSelectedValues(); xyz(); } – Sumeet Hiremath Mar 05 '15 at 05:42
  • @SumeetHiremath - Debug your code and definitely you'll be able to recognize the bug. Check this link - http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it to know the cause for this issue. Please try to fix and if you are really stuck hard only then post new question. – Rahul Singh Mar 05 '15 at 05:47