Click here to Skip to main content
15,879,348 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
That's the error I get. I understand this error means that one of the numbers is out of range--BUT ITS NOT! Here's my first code snippet (trying to get the last four characters out of 'Label1', using a substring. I call this substring "filetype"):

VB
filetype = Label1.Text.Substring(Label1.Text.Length - 4,_ Label1.Text.Length)



This error is pretty much saying that the length of Label1 exceeds the length of Label1. Makes no sense. I was afraid that Label1 actually has no value when I call the substring, so I thought what I should use to get the text should be what Label1 uses to get its text. Label1 uses Form1.ListBox2.SelectedItem. So, my second code snippet:


VB
filetype = Form1.ListBox2.SelectedItem.ToString.Substring(Form1.ListBox2.SelectedItem.ToString.Length - 4, Form1.ListBox2.SelectedItem.ToString.Length)



And I get the same error. So then I look at the details, and it says that Label1's text is 51 characters. So, my third code snippet, just to test it:


VB
filetype = Label1.Text.Substring(47, 51)



AND BELIEVE IT OR NOT, I GET THE SAME ERROR! It clearly says the length is 51. I'm just so stumped.

So thanks for reading my whole question.

Bill
Posted

Hi,

Your code snippet:
C#
filetype = Label1.Text.Substring(47, 51);

The startIndex is 47, and the length is 51. 51 isn't where the substring needs to end. 51 is the length of the substring you want to take.
Read more here:
http://msdn.microsoft.com/en-us/library/aka44szs.aspx[^]
 
Share this answer
 
v2
OK, unless I'm missing something obvious then it's simply that you've misinterpreted the second parameter.
it's the length of the string you want to extract, not the length of what you started with.
VB
"TheBilly102030".Substring(3, 5) = "Billy"

VB
"TheBilly102030".Substring(14 - 4, 14) = Error
Since you are asking it to grab 14 characters from a 14 character string starting at position 10, so it goes looking for characters between 10 and 24, most of which don't exist...

If what you want is the last three characters, or the last four, ot everything after the last "." then:

VB
Dim filename as string = "TheBilly102030.doc"
'Change 3 to 4 for a 4 character file extension
Dim filetype as string = filename.Substring(filename.length - 3, 3) = "doc"

The variable version is done simply by grabbing the position of the last "." and substituting that for the literal number used above.

MSDN[^]

Mike
 
Share this answer
 
Thanks SO MUCH! It works perfectly now!!!
 
Share this answer
 

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