Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index and length must refer to a location within the string. Parameter name: length

I'm getting this error:

Index and length must refer to a location within the string.
Parameter name: length

Using this code:

string a1 = ddlweek.Text.Substring(0, 8);                
string a3 = ddlweek.Text.Substring(10, 14);

What does this mean?

like image 770
Zoya Mehta Avatar asked May 16 '12 08:05

Zoya Mehta


2 Answers

If the length of your string (ddlweek) is 23 characters or less, you will get this error:

    string ddlweek = "12345678901234567890123";//This is NOK
    string a1 = ddlweek.Substring(0, 8);                
    string a3 = ddlweek.Substring(10, 14);
    Console.WriteLine("a1="+a1);
    Console.WriteLine("a3="+a3);
    Console.ReadLine();

The string should be at least 24 characters long.. You might consider adding an if to make sure everything is OK..

    string ddlweek = "123456789012345678901234";//This is OK
    string a1 = ddlweek.Substring(0, 8);                
    string a3 = ddlweek.Substring(10, 14);
    Console.WriteLine("a1="+a1);
    Console.WriteLine("a3="+a3);
    Console.ReadLine();
like image 138
dincerm Avatar answered Oct 31 '22 20:10

dincerm


Substring(startIndex,length);

startIndex : Gets the first value you want to get. 0 Begins.

length : The size of the value you get (How many digits you will get).

string Code = "KN32KLSW";
string str = Code.Substring(0,2);
Console.WriteLine("Value : ",str);

On the Console screen : KN

string str = Code.Substring(3,4);
Console.WriteLine("Value : ",str);

On the Console screen : 2KLS

like image 25
ihsan güç Avatar answered Oct 31 '22 22:10

ihsan güç