1

I have an array like this that saves queries as the user moves forward:

String [,] qArr=new String[2,6];

I have a button for each of those 6 rows in the array.
Here is what I want to do:
If the user is at step 4 (button 4 and so 8 queries saved), now clicks on button 2, then I want to delete any query after row 2 in the array.
Here is what I have done:

public void remQ(int position) //position is the row starting from 0   
{  
position=(position+1)*2;  
Array.Clear(qArr,position,qArr.Length);    
} 

Error1: Here is what I get when I run this:

Index was outside the bounds of the array

Debugging shows these values:

qArr=string[2,6]   
d=4   
qArr.Length=12

How do i fix this?

3
  • 1
    You should not use qArr.Length, you should tell qArr.Length - position to have the number of elements you want to clear. Commented Feb 2, 2018 at 20:29
  • 1
    A question should be limited to one question. If you have a new question (as you do here) then ask a new question, don't edit the current one. Otherwise answers which previously answered your question are no longer complete. As it is I can give you the quick hint that swapping your array to a string [6,2] would probably exhibit the behaviour that you want. Commented Feb 2, 2018 at 21:50
  • @Chris I wasnt sure if I should start a new one because the question did not change, just the error did. Anyway, I reverted it back. Thanks for the quick hint, will try it out. Commented Feb 2, 2018 at 21:58

1 Answer 1

1

Have you read https://msdn.microsoft.com/en-us/library/system.array.clear(v=vs.110).aspx and what can cause that exception?

"The sum of index and length is greater than the size of array."

You are passing the length as the total length of the array. Unless you are starting at index 0 then you will not be clearing all of the items. You need to correctly calculate how many items you want to clear:

Array.Clear(qArr,position,qArr.Length-position); 
Sign up to request clarification or add additional context in comments.

3 Comments

I did read it, but clearly misunderstood it. I did the fix before you added the code by reading your description. Worked! Thanks!
Glad to hear it. I figured that it wasn't hard to work out what to do but the answer would be more complete with it. Feel free to upvote/accept to show your appreciation (though you may have to wait a while before you can accept). :)
That fixed the error I was getting but what I want to do in the question is still not happening. The method removes all values from column 2 and leaves all the ones in column 1. Any ideas?

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.