C# Aligning 2 Strings via a listbox
In my listbox, I would like to display the following
String 1(left aligned - default) int value(right aligned)
Is there a way to do this, or can there only be 1 alignment in a listbox?
Answers
If you are Using in Winforms, you can use this code.
You can set the DrawMode property of the ListBox to DrawMode.OwnerDrawFixed
ListBox listBox = new ListBox(); listBox.DrawMode = DrawMode.OwnerDrawFixed; listBox.DrawItem += new DrawItemEventHandler(listBox_DrawItem); void listBox_DrawItem(object sender, DrawItemEventArgs e) { ListBox list = (ListBox)sender; if (e.Index > -1) { object item = list.Items[e.Index]; e.DrawBackground(); e.DrawFocusRectangle(); Brush brush = new SolidBrush(e.ForeColor); SizeF size = e.Graphics.MeasureString(item.ToString(), e.Font); e.Graphics.DrawString(item.ToString(), e.Font, brush, e.Bounds.Left + (e.Bounds.Width / 2 - size.Width / 2), e.Bounds.Top + (e.Bounds.Height / 2 - size.Height / 2)); } }
If you use WPF. This should work in XAML:
<ListBox.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinition> <ColumnDefinition Width="Auto" MinWidth="100"/> <ColumnDefinition Width="Auto" MinWidth="100"/> </Grid.ColumnDefinition> <TextBlock Text="{Binding 1}" HorizontalAlignment="Left"/> <TextBlock Text="{Binding value}" HorizontalAlignment="Right" Grid.Column="1"/> </Grid> </DataTemplate> </ListBox.ItemTemplate>
Out of memory! You may have to adjust it a bit.
By the way: Variable names like "1" and "value" belong to the category of bad naming ;-) Hope it was just for the post and not for your real working code.
Next time you can also make clear in which technology you want it to display (WinForms, WPF, ASP.net, etc.).
Christoph