If: Index and length must refer to a location within the string. (Parameter 'length')

Hello,
I have the following error message that I cannot resolve. Can someone help me. THANKS

the module works without problem on a PC with Widnows 10, but it displays this message on Windows 11

.

This error usually means that you are trying to access a substring or character from a string, but the index or length you have provided is beyond the range of the string’s actual length.

For example, if you have a string of length 5 and you’re attempting to access the substring from index 6 to 7, it would throw this error because the indices 6 and 7 do not exist in the string.

To fix this issue, you should ensure that the start index and length you’re providing are within the valid range of the string’s length. You might need to add conditions to check the string’s length before performing such operations.

Here’s an example of incorrect usage:

string str = "Hello";
string subStr = str.Substring(6, 2);

And here’s the corrected code:

string str = "Hello";

if (str.Length >= 8) // or any condition that makes sense in your context
{
    string subStr = str.Substring(6, 2);
}

Remember the first position of a string is 0, not 1. In C#, string.Substring takes two parameters–the start index and the length of the substring–both should be within the range of the string. Another important thing to consider is that the ‘start index’ is inclusive, but the ‘end index’ is exclusive.

here is the text that I want to compare “000330562/36154/10EA” to this one: “000330562/36”

I want to compare only the first 12 characters

It make sense invert your logic ?

CurrentText.ToString.StartsWith(yourRowText)

So you don’t need to do extra validation

but why doesn’t it work ?

As mentioned by Marian your string is smaller than the size of the piece you want to extract

You can run in debug mode and look at locals pane or imediate to validate the string size before substring method

ok guys, thanks. I added a “Substring” step before “if” and it works.