Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
string sub1 = (Convert.ToString(dateTimeDate.Value)).Substring(3, 2);
           string sub2 = (Convert.ToString(dateTimeDate.Value)).Substring(8, 2);
           txtRefNo.Text = sub1 + sub2;

             string sub = comboDescription.Text.Trim();

               if (comboDescription.SelectedIndex > -1 || sub != string.Empty)
               {
                   sub = (Convert.ToString(sub)).Substring(0, 3);
                   txtRefNo.Text = txtRefNo.Text + sub;
               }


Above is code that i am calling on event
C#
comboDescription_SelectedIndexChanged(object sender, EventArgs e)


My problem is that this caused exception
C#
Index and length must refer to a location within the string.
Parameter name: length
how can i get the required value in same event.
Posted

1 solution

Your error, I would guess, occurs on one of these three lines:
C#
string sub1 = (Convert.ToString(dateTimeDate.Value)).Substring(3, 2);

C#
string sub2 = (Convert.ToString(dateTimeDate.Value)).Substring(8, 2);

or
C#
sub = (Convert.ToString(sub)).Substring(0, 3);


Before you attempt any substring function, check the length of the string you are trying to extract. If it is less than either the index you are starting with or the index plus X characters you are trying to extract then it will fail.

For example you could try:


C#
string sub2 = (Convert.ToString(dateTimeDate.Value));
sub2 = sub2.length > 9 ? sub2.Substring(8, sub2.length > 11 ? 2 : (sub2.length-1)-8) : "";


What this would do is check to see if sub2 has a length more than 9 (i.e. it has a possible starting index of 8 as per your code. Then it looks to see what length it can extract, be it 1 or 2 characters. If it cannot extract the sub string it sets sub2 equal to "".

I'm not 100% on the code but its just a concept for you to work with.
 
Share this answer
 
Comments
Maciej Los 19-Apr-13 5:30am    
Nice, +5!
pck.ns 20-Apr-13 7:57am    
Thanks for your help ...your concept is good

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