Thursday, June 21, 2007

ASP.NET GridView Locale Issues

Last month we had strange problems using ASP.NET GridView component (accompanied with ObjectDataSource). String fields were O.K., but when creating or updating double field, exceptions arised.

The problem was, that GridView in this configuration (didn't tried with different type of DataSource), ignored locale settings, so typing numeric values with comma (or dash if you want) instead of period (point) produced exception. Using period caused this problem (when editing stored values, which where in business automatically converted to commas) also.

One quick solution was to switch the whole thread to the US locale, but that later caused some interferences with different parts of the code.

Luckily, I have somewhere (sorry, couldn't remember where) found the way to customize the conversion of data in GridView. It goes as follows (in VB.NET):

Simply create an ItemInserting event handler for the GridView and for all problematic values make the conversion as you need.


Protected Sub GridView_ItemInserting
(ByVal sender As Object,
ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs
)
Dim myconverter As System.ComponentModel.TypeConverter =
System.ComponentModel.TypeDescriptor.GetConverter(
GetType(Double))

e.Values("FieldName") =
myconverter.ConvertFromString(
CType(e.Values("FieldName"), String))
End Sub


That's all folks.

No comments: