Justin Fox
Justin Fox

Reputation: 3

Align a part of the string in a ListBox Item to the right c#

I have created a ListBox and added a item(observed) but I want a part of the string to be aligned to the right(expected). I have tried adding a right to left unicode but that doesn't work. The code is a normal listbox.

Thanks for your help!

Edit: It is a winforms application with just a listbox and this line of code:

listBox1.Items.Add("Justin Fox 102304506");

Upvotes: 0

Views: 1224

Answers (2)

Nemo
Nemo

Reputation: 203

you can use something like this

String.Format("{0,-10} | {1,20}", "Nemo", "Mo")

by this format you'll get "Mo" aligned to right on 20 characters

listBox1.Items.Add(String.Format("{0,-10} | {1,20}", "Nemo", "Mo"));

Upvotes: 1

st_stefanov
st_stefanov

Reputation: 1186

I am not sure that there is out-of-the-box solution for this. If you want to go with a workaround you can try something like this.

(Suppose your listbox has fixed width). You measure how many symbols are needed to fill the width of the list box. Say it is 100 symbols. You already have 2 elements, one that is aligned to the left and the other aligned to the right. Count their characters and pad with zeroes the first one.

var s1Length = string1.Length;
var s2Length = string2.Length;
var itemToAdd = string1.PadLeft(100 - (s1Length  + s2Length ), ' ') + string2;
listbox.Items.Add(itemToAdd);

Upvotes: 0

Related Questions