Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting strings in a mutiline TextBox

I would like to add 3 strings to a multiline TextBox in this format:

  str1:    3000
 srr22:   23044
str333:  222222

I need to align these strings in the TextBox to the right.

I have tried this code:

Dim s1 As String = " str1: "
Dim n1 As Integer = 3000

Dim s3 As String=vbCrLf & String.Format("{0,15}", s1) & String.Format(" {0:d6}", n1)
txtKopfring.Text = s3
s1 = "str22: "
n1 = 23044

s3 = s3 & vbCrLf & String.Format("{0,15}", s1) & String.Format("{0:d6}", n1)
txtKopfring.Text = s3

s1 = "str333: "
n1 = 222222

s3 = s3 & vbCrLf & String.Format("{0,15}", s1) & String.Format("{0:d6}", n1)
txtKopfring.Text = s3

The output however was not as expected, could you provide hints to get the output correct?

like image 770
waleed almukawi Avatar asked Mar 14 '26 10:03

waleed almukawi


1 Answers

First, change the font to a fixed-width font. I chose Courier New.

Now for this to work you need to know what the max length is of your numbers. In your example this is 222222 which has a length of 6.

To achieve this what I did was add the numbers to a Dictionary:

Dim numbers As New Dictionary(Of String, Integer)
numbers.Add("str1: ", 3000)
numbers.Add("str22: ", 23044)
numbers.Add("str333: ", 222222)

I then found the max length of the .Values collection to work out which number had the largest length, padding out the numbers using the maxLength:

Dim maxLength As Integer = numbers.Values.Max.ToString.Length

The next job was to loop through the Dictionary and add the values to a StringBuilder:

'Import System.Text
Dim sb As New StringBuilder

For Each number As KeyValuePair(Of String, Integer) In numbers
    sb.AppendLine(String.Format("{0,15}", number.Key) & String.Format("{0:d6}", number.Value.ToString.PadLeft(maxLength)))
Next

To use a StringBuilder you will have to import System.Text.

Lastly:

txtKopfring.Text = sb.ToString()

This gives me the following output:

enter image description here

If you didn't want to follow my logic, to achieve what you are after in your code, you can change:

String.Format(" {0:d6}", n1)

To:

String.Format("{0:d6}", n1.ToString.PadLeft(6))

Note the 6 is hardcoded and not recommended as other values may come into play which could be longer in length and will throw the formatting out.

Also I have copied your code directly from your question and noticed a slight issue.

This String.Format(" {0:d6}", n1) has a space in the first argument and that will be potrayed in your formatting. Remove the space like such String.Format("{0:d6}", n1).

like image 79
Bugs Avatar answered Mar 16 '26 00:03

Bugs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!