0

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] = answer 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

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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++;
    }

2 Comments

Wow I think Spencer revenge downvoted me because he didn't like my comment pointing out his error. Then he deleted his post in embarrasment. Guess he took his ball and went home :)
+1 to negate a downvote you didnt deserve :). Happens to me all the time.
1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.