Theo Robins
Theo Robins

Reputation: 9

How to work with substrings in VB?

It won't let me put in a surname less than five letters

    Dim firstintial As String 
    Dim form As String
    Dim secondname As String


    form = TextBox3.Text
    firstintial = TextBox4.Text
    secondname = TextBox5.Text

    firstintial = firstintial.Substring(0, 2)
    secondname = secondname.Substring(0, 5)


    Dim newusername As String
    newusername = form & secondname & firstintial
    TextBox6.Text = newusername

    Dim newpassword As String
    newpassword = TextBox7.Text
    TextBox8.Text = newpassword



    If TextBox7.Text = TextBox12.Text Then
        Label13.Text = "correct"
    Else
        Label13.Text = "try again"

Upvotes: 0

Views: 86

Answers (3)

Andrew Morton
Andrew Morton

Reputation: 25066

Although many people frown upon using Visual Basic-specific methods instead of .NET framework methods, you can use Left, which takes care of the requested length being greater than the length of the string:

secondname = Left(s, 5)

However, if you are using it in code on a control, the Control.Left property gets chosen in preference, so you need to qualify it:

secondname = Strings.Left(s, 5)

Upvotes: 1

Craig
Craig

Reputation: 2494

You can use Linq's Take to get up to number of characters without an explicit test:

Dim firstinitial = New String(TextBox4.Text.Take(2).ToArray())
Dim secondname = New String(TextBox5.Text.Take(5).ToArray())

I would expect this to be less efficient than the Substring-based code, so be careful about using it in a tight loop, but it should be just fine for something that looks like it's done in one pass.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460288

Substring doesn't like if index + length indicates a position outside of the string.

Dim length = Math.Min(firstintial.Length, 2)
firstintial = firstintial.Substring(0, length)
length = Math.Min(secondname.Length, 5)
secondname = secondname.Substring(0, length)

Upvotes: 1

Related Questions