ObjectDataSource UK Date bug - a workaround
OK, so the first time I get to play with the ObjectDataSource for binding my gridview on my asp.net application...I find a bug! - typical
It appears that the culture information seems to be ignored when firing the object update command. This may mean nothing to you if you are a user in the states using the en-US culture, but for us guys over here in the UK who use the en-GB culture this is a seriosu problem as we will edit our dates in the UK format but when we go to update the row, we will ge the following error...
Cannot convert value of parameter 'dtyourdatefield' from 'System.String' to 'System.DateTime'
So I did a google..as you do and found Microsoft's visual studio team have acknowledged this as a bug but won't fix it as thy say the workaround is much easier to implement than the fix...hmm....
So I have to work around this problem by writing my own code so here is my implementation of a workaround:
1: Private Function ParseNewGridValues(ByVal pe As System.Web.UI.WebControls.GridViewUpdateEventArgs) As System.Web.UI.WebControls.GridViewUpdateEventArgs
2: Dim oValue As System.Collections.DictionaryEntry
3: For Each oValue In pe.NewValues
4: If IsDate(oValue.Value) Then
5: Dim oGB As New Globalization.CultureInfo("en-GB")
6: Dim oUS As New Globalization.CultureInfo("en-US")
7: Dim dtParsed As DateTime = DateTime.Parse(oValue.Value, oGB)
8: Dim tFormatted As String = dtParsed.ToString("yyyy-MM-dd HH:mm:ss", oUS)
9: pe.NewValues(oValue.Key) = tFormatted
10: End If
11: Next
12: Return pe
13: End Function
14:
15: Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
16: e = ParseNewGridValues(e)
17: End Sub
As you can see form the code, I handle the row updating event and go run a function which converts the date values in my datagrid form UK (how my data gets selected as!) back to an Isodate format using the en-US culture. We then save the new converted date values back to the original event arguments (NewValuesauesnewvalues collection). easy! right???!
If you are interested…here is the bug documentation from MSFT
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=105016
Please let me know if anyone finds a better more elegant way to handle this!