Using the CultureInfo ClassThe CultureInfo class contains information about more than 150 different cultures. You can use the methods of this class in your code to retrieve information about a specific culture and use the information when formatting values such as dates, numbers, and currency amounts. To represent a culture with the CultureInfo class, you can instantiate the class by passing a culture name to the class constructor like this: Dim culture As New CultureInfo("de-DE") You can also use any of the following methods of the CultureInfo class to retrieve information about a culture or cultures:
The CultureInfo class lives in the System.Globalization namespace. Before you can use the CultureInfo class, you need to import this namespace. Using the CultureInfo Class to Format String ValuesTo this point, the culture has been set at the level of an individual ASP.NET page or the level of an entire ASP.NET application. However, you might need to take advantage of locale-specific formatting at a more granular level. You can use the CultureInfo class to format a particular value independent of the Culture set for the page. When you use the ToString() method to format dates, times, numbers, and currency amounts, you can supply an additional parameter that formats the value in accordance with a specific culture. For example, the page in Listing 24.9 formats two sets of date and time values. Listing 24.9. ToStringCulture.aspx
The first date and time is formatted with German cultural conventions, and the second date and time is formatted with Indonesian cultural conventions (see Figure 24.7). Notice that two CultureInfo objects, corresponding to two cultures, are created in the Page_Load() method. Figure 24.7. Formatting with the ToString() method.Comparing and Sorting String ValuesDifferent cultures follow different conventions when comparing and sorting string values. If you need to compare or sort string values in your code, then you should use the String.Compare() method and optionally supply the method with an instance of the CultureInfo object. The String.Compare() method returns one of the following values:
For example, the following conditional compares two strings, using the current culture set for the page: If String.Compare("Hello", "Hello") = 0 Then lblResult.Text = "The strings are the same!" End If The following conditional uses a specific culture to perform a string comparison: If String.Compare("Hello", "Hello", True, New CultureInfo("de-DE")) = 0 Then lblResult.Text = "The strings are the same!" End If In this case, the first two parameters passed to the String.Compare() method are the strings being compared. The third parameter indicates whether the comparison performed should be case sensitive or not. Finally, the last parameter represents a CultureInfo object. |