Title: Storing cookie in string array variable and displaying the string
Tags: c#;asp.net;arrays;cookies
Question: 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]);

Here is the accepted answer: 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.
Comment for this answer: @BillK - Yup thnx! Updated.
Comment for this answer: @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.
Comment for this answer: @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();
Comment for this answer: Or, just change <= to =


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:03/05/15', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<c#><asp.net><arrays><cookies>', 'Title': 'Storing cookie in string array variable and displaying the string', 'ViewCount': 1597, 'id': 28870376, 'user_AboutMe': '', 'user_AccountId': 5540454.0, 'user_DisplayName': 'Sumeet Hiremath', 'user_Reputation': 67.0, 'user_Views': 32.0, 'user_id': 4397182.0}}