Title: Format values in a ListBox in C#
The ListBox control's FormatString property determines how the control formats the values it displays. This can be particularly useful if you need to display values that need special formatting such as dates and currency amounts.
When it starts, this example uses the following code to display formatted values.
private void Form1_Load(object sender, EventArgs e)
{
double[] prices =
{
13.38, 7.75, 50.61, 532.21, 8.29, 111.11, 962.38,
49.27, 4.06, 98.45, 896.13, 7.51, 592.09, 238.29,
};
lstC.FormatString = "C";
lstC.RightToLeft = RightToLeft.Yes;
lstC.DataSource = prices;
DateTime[] dates =
{
new DateTime(2013, 4, 1),
new DateTime(2013, 3, 21),
new DateTime(2013, 7, 18),
new DateTime(2013, 9, 9),
new DateTime(2013, 11, 30),
new DateTime(2013, 2, 12),
new DateTime(2013, 4, 1),
new DateTime(2013, 3, 21),
new DateTime(2013, 7, 18),
new DateTime(2013, 9, 9),
new DateTime(2013, 11, 30),
new DateTime(2013, 2, 12),
};
lstNone.RightToLeft = RightToLeft.Yes;
lstNone.DataSource = dates;
lstD.FormatString = "D";
lstD.RightToLeft = RightToLeft.Yes;
lstD.DataSource = dates;
}
The code first creates an array of doubles. It sets the lstC ListBox control's FormatString property to C so it displays the values as currency. The code also sets the control's RightToLeft property to Yes so the values are aligned on the right. It then sets the control's DataSource property to the array of values so the control displays them.
Next, the program creates a list of dates. It sets the lstNone ListBox control's LeftToRight property to Yes and sets its DataSource property so the control displays the dates. The program doesn't set the control's FormatString property so it displays the values with their default formatting.
The program finishes by displaying the same dates but using the D long date format.
Download the example to experiment with it and to see additional details.
|