Click here to Skip to main content
15,919,028 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
System.ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length at System.String.Substring(Int32 startIndex, Int32 length) at ScholarFormDetail1112122.btn_submit_Click(Object sender, EventArgs e)


What I have tried:

System.ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length at System.String.Substring(Int32 startIndex, Int32 length) at ScholarFormDetail1112122.btn_submit_Click(Object sender, EventArgs e)
Posted
Comments
Richard MacCutchan 16-Dec-23 7:25am    
The error message is clear either your index is negative, or the index plus the length is greater than the length of the string.

1 solution

Have a look to the following examples:
public class Program
{
	public static void Main()
	{
		string test= "0123456789";
		
		// 1.) Will fail, because max. Index will be 9
		// string subString0= test.Substring(10, 1);
		
		// 2.) Ok
		string subString1= test.Substring(9, 1);
		
		// 3.) Will fail because  there is only one character available. See note *1)
		// string subString2= test.Substring(9, 100);

		// 4.) Ok
		string subString3= test.Substring(9, 1);
	}
}


Note *1)
It is questionable to throw in that case an exception. Most other languages will simply return the available characters.

[Edit]
Note *1) , Thanks to Richard for his hint.
Some languages do not throw an Exception in that case.

I hope it helps.
 
Share this answer
 
v4
Comments
Richard MacCutchan 16-Dec-23 9:26am    
It is correct to throw an exception, as there may well be other more serious side effects if the values are out of range.
0x01AA 16-Dec-23 9:27am    
As I mentinoed, most languagues do not throw an exception in that case ;)
Richard MacCutchan 16-Dec-23 9:45am    
I would say that most languages do throw an exception in that case. Which specific languages are you referring to?
0x01AA 16-Dec-23 9:56am    
Ok, I was something blind. I was focused on my c++ environement and js.
I will edit my answer.
Thanks a lot.
Dave Kreskowiak 16-Dec-23 12:16pm    
An exception would only be thrown in the language supports checking the index against the bounds of the array. In older languages, this doesn't happen, but in newer languages it does. One reason for that is because of security concerns, like buffer overruns.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900