Set the DataTable.Locale property – or get weird sorting

If you have a monster of an ASP.NET app, and your user come from different places in the world, they are most likely to have different locales as well. I’m danish, and we have three special characters in our alphabet – æ, ø, å. If I have a DataTable with – let’s say firstname and lastname columns. I create my DataTable like this:

DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("Firstname", typeof(string))); dt.Columns.Add(new DataColumn("Lastname", typeof(string))); dt.Rows.Add(newobject[] { "Øjvind", "Jensen" }); dt.Rows.Add(newobject[] { "John", "Nielsen" }); dt.Rows.Add(newobject[] { "Åse", "Østergaard" });

This is how I DataBind my GridView:

if (!Page.IsPostBack) { GridView1.DataSource = dt.DefaultView; GridView1.DataBind(); }

With my regional settings on my machine (which in this case is also the webserver) we get the correct sorting:

The GridView sorted by Firstname ascending.

But if I go ahead and change the settings of my machine, to English (United States), my GridView will look like this, when I sort it by Firstname ascending:


This is because the server compares the strings wrong. So if you’re dealing with users from around the globe – you have to set the Locale property of the DataTable – this is done like this:

dt.Locale = System.Globalization.CultureInfo.CurrentCulture;

Now this I cannot test on a single machine. This is because the above code takes the CultureInfo of your machine, and since I just changed my regional settings, I get the GridView sorted wrong. So I fired up my old laptop, this time with FireFox the GridView looks like this:


From a user perspective, a GridView sorted incorrectly is very bad. So to add this single line of code is really not a big deal.

Technorati Tags: [ASP.NET](, [C#](, [DataTable](, [CultureInfo](