ASP.Net c# adding items to jagged array
im trying to add items to jagged array's, the data is being pulled from a datarowview, i have the following code
foreach (DataRowView answer in AnswersInQuestion)
{
answersJArray[index] = new string[noOfAnswersInQuestion];
answersJArray[index][j] = answer["ChoiceText"].ToString();
j++;
}
the first item gets added in fine, but when the 2nd item is put in the first item is set to null again. so for example the first time round this is what the array will look like
arr[0][0] = answe开发者_开发技巧r 1
arr[0][1] = null
arr[0][2] = null
arr[0][3] = null
and the 2nd time round the array will look like
arr[0][0] = null
arr[0][1] = answer 2
arr[0][2] = null
arr[0][3] = null
can any one help me on this !!
thanks
Your constructor is being called each time (hence the first item being set to null). Put your string array constructor outside of your for-each loop (perhaps in its own loop.
You need a nested loop, because you are creating a brand new array each time and blowing the old one away.
//souround with a loop that increments index whenever you want to create a new group of questions
answersJArray[index] = new string[noOfAnswersInQuestion];
foreach (DataRowView answer in AnswersInQuestion)
{
answersJArray[index][j] = answer["ChoiceText"].ToString();
j++;
}
What is index? You don't seem to be incrementing it, and each time through your foreach you're creating a new one and dumping it into the same index. Basically rewriting it each time.
You might find more use in using a List to accomplish this jagged array. It will make adding/removing a little easier, and it might help a touch in enumerating.
My approach is to create a hashset of string arrays then populate at will, and at the end, convert ToArray()
e.g.
HashSet<string[]> data = new HashSet<string[]>();
data.Add(new string[] { "mode", "create" });
data.Add(new string[] { "title", this.TextBoxCreateTitle.Text });
data.ToArray(); // our jagged array
精彩评论