Click here to Skip to main content
11,715,165 members (60,954 online)
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 22:32pm
pck.ns689

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 Sergey Alexandrovich Kryukov 495
1 Richard MacCutchan 275
2 Maciej Los 259
3 ManasKumarM 155
4 Frankie-C 125
0 Sergey Alexandrovich Kryukov 775
1 CHill60 415
2 Richard MacCutchan 405
3 Maciej Los 389
4 OriginalGriff 320


Advertise | Privacy | Mobile
Web04 | 2.8.150901.1 | Last Updated 19 Apr 2013
Copyright © CodeProject, 1999-2015
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