pk_code
pk_code

Reputation: 2776

Managing Space between 2 words in same string in c#

I have list of string in which I am adding location and its zip code dynamically,

and I am populating that list in text box with scroll bar. But I get space between location and zip code depending on location length,

for example :

   Chicago     60016
   Niles     12332
   San Francisco 95858

What I want is

  Chicago       60016
  Niles         12332
  San Francisco 95858

Here is my code :

var List<string> CityZip = new List<string>();

foreach(var item in CollectionofCityZip)
{
  CityZip.Add(item.City + "    " + item.Zip);

}

Update

I tried CityZip.Add(item.City.PadRight(14) + item.Zip);

It gave me :

   Chicago     60016
   Niles     12332
   San Francisco    95858

But I want

  Chicago       60016
  Niles         12332
  San Francisco 95858

Upvotes: 1

Views: 2299

Answers (3)

David
David

Reputation: 5003

If you are using a monospaced font (each letter is the same width) then you can use the built in PadRight function which will pad the string with spaces to be the length you specify:

CityZip.Add(item.City.PadRight(14) + item.Zip);

Note the 14 there is arbitrary. If you want to line it up just right, you'll need to scan your list first and see how long the longest string is and pad to that length. Something like this should work:

const int extraPadding = 1; // how much space to put after the longest entry
int maxLen = CollectionOfCityZip.Select(item => item.City.Length).Concat(new[] {0}).Max();
CityZip.Add(item.City.PadRight(maxLen + extraPadding) + item.Zip);

Upvotes: 2

DasKr&#252;melmonster
DasKr&#252;melmonster

Reputation: 6060

If you use WPF, you can specify an item template for the Listbox that could look something like this:

<ListBox.ItemTemplate>
    <DataTemplate>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <TextBlock Grid.Column="0" Text="{Binding Data}"></TextBlock>
            <TextBlock Grid.Column="1" Text="x"></TextBlock >
        </Grid>
    </DataTemplate>
</ListBox.ItemTemplate>

If you are using Winforms, the monospaced font with a variable number of spaces is the simplest solution. Alternatively you can draw the entries yourself.

Relevant MSDN

Relevant SO

Upvotes: 2

Serj-Tm
Serj-Tm

Reputation: 16981

C# 6.0:

   CityZip.Add($"{item.City,-14}{item.Zip}");

C# < 6.0:

   CityZip.Add(string.Format("{0,-14}{1}", item.City, item.Zip));

Upvotes: 0

Related Questions