[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Display sample formats for different locales in C#

[Display sample formats for different locales in C#]
This example loops through the system's defined locales and displays sample numbers, currency values, dates, and times in each.

When the program starts, the following code executes.

private void Form1_Load(object sender, EventArgs e) { float float_value = 1234.56f; decimal dec_value = 1234.56m; DateTime now = DateTime.Now; // Loop through the locales. foreach (CultureInfo info in CultureInfo.GetCultures(CultureTypes.AllCultures)) { ListViewItem item = lvwResults.Items.Add( info.EnglishName); item.SubItems.Add(info.NativeName); item.SubItems.Add(info.Name); // You can't use a neutral culture as a format // provider, so if the CultureInfo is neutral, // look for a non-neutral ancestor. CultureInfo culture = info; while ((culture != null) && (culture.IsNeutralCulture)) culture = culture.Parent; if (culture != null) { item.SubItems.Add(float_value.ToString("N", culture)); item.SubItems.Add(dec_value.ToString("C", culture)); item.SubItems.Add(now.ToString("d", culture)); item.SubItems.Add(now.ToString("t", culture)); } } }

This code first creates float, decimal, and DateTime sample values. It then loops through the CultureInfo objects returned by CultureInfo.GetCultures.

For each CultureInfo, the code adds the object's English, native, and locale names to the ListView.

Next the code checks whether the object represents a neutral culture such as en. If it does, the object doesn't contain information about a specific culture that is needed to format values. For example, the culture en doesn't contain that information. In contrast, a specific culture such as en-US or en-GB.

If the object does represent a neutral culture, the code climbs up its parent hierarchy until it finds a non-neutral culture and it uses that one.

Having found a non-neutral culture, the program uses the culture to format float, decimal, date, and time values and adds them to the ListView.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.