Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#4.0 WinForm
 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
 comboDescription_SelectedIndexChanged(object sender, EventArgs e)

 
My problem is that this caused exception
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 18-Apr-13 23:32pm
pck.ns558

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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

or
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:
 

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.
  Permalink  
Comments
Maciej Los at 19-Apr-13 5:30am
   
Nice, +5!
pck.ns at 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)

  Print Answers RSS
0 Mathew Soji 274
1 BillWoodruff 270
2 Afzaal Ahmad Zeeshan 244
3 Sergey Alexandrovich Kryukov 240
4 Raul Iloc 160
0 OriginalGriff 6,219
1 Sergey Alexandrovich Kryukov 5,853
2 DamithSL 5,103
3 Manas Bhardwaj 4,549
4 Maciej Los 3,845


Advertise | Privacy | Mobile
Web04 | 2.8.1411019.1 | Last Updated 19 Apr 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100