Truncate String

C

cmdolcet69

The code below is suppose to work were if a user enters a value in the
text box > 12 characters long it will hit this loop and truncate the
value to only 12 characters long....however this doesn;t happen...what
do i need to do?

If txtRightLabel.Text.Substring(0, 12) Then
Dim Righttextlable As String
Righttextlable = txtRightLabel.Text
txtRightLabel.Text =
Righttextlable.Substring(Righttextlable.Length - 12)
End If
 
G

Göran Andersson

cmdolcet69 said:
The code below is suppose to work were if a user enters a value in the
text box > 12 characters long it will hit this loop and truncate the
value to only 12 characters long....however this doesn;t happen...what
do i need to do?

If txtRightLabel.Text.Substring(0, 12) Then

Two errors:

1. The expression returns a string, which you use as a condition in the
If statement.

2. If the text is shorter than 12 characters you will get an exception
when you try to get the first 12 characters.
Dim Righttextlable As String
Righttextlable = txtRightLabel.Text
txtRightLabel.Text =
Righttextlable.Substring(Righttextlable.Length - 12)

This would not make the string 12 characters long, it would shorten the
string by 12 characters.

From your specification, this is what you want:

If txtRightLabel.Text.Length > 12 Then
txtRightLabel.Text = txtRightLabel.Text.Substring(0, 12)
End If

or:

txtRightLabel.Text = txtRightLabel.Text.Substring(0,
Math.Min(txtRightLabel.Text.Length, 12))

Or why not simply limit the text box to 12 characters?

txtRightLabel.MaxLength = 12
 
O

\(O\)enone

Göran Andersson said:
or:

txtRightLabel.Text = txtRightLabel.Text.Substring(0,
Math.Min(txtRightLabel.Text.Length, 12))

or:

txtRightLabel.Text = Strings.Left(txtRightLabel.Text, 12)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top