Handling e.value = nothing

Handling e.value = nothing

Old forum URL: forums.lhotka.net/forums/t/1241.aspx


MadGerbil posted on Monday, September 18, 2006

On a csla datasource UpdateObject event if an e.value is nothing and I try to convert it to a string I get an error.  This happens when an object populated with string values is bound to the webform and the user deletes all the text in one of the bound textboxes. 

The empty string causes the following to error:

child.EmployeeName = (Ctype(e.Values("EmployeeName"), String))

How should this be handled?

MadGerbil replied on Monday, September 18, 2006

What is bizzare about this to me is that the InsertObjectArgs returns an empty string "" if the value is left blank.  The UpdateObjectArgs returns Nothing.  Because of this, one handles the empty strings and the other does not.

RockfordLhotka replied on Monday, September 18, 2006

Yeah, I've run into that as well. It appears that ASP.NET data binding is kindly changing empty string values to Nothing/null. Rather a PITA if you ask me...

The only solution I'm aware of in C# is to check for the null, but in VB life is a bit simpler because VB will help you out if you use the VB runtime:

child.EmployeeName = CStr(e.Values("EmployeeName"))

If you dislike using the Basic runtime, then you can write the code C#-style:

If e.Values("EmployeeName") IsNot Nothing Then
  child.EmployeeName = DirectCast(e.Values("EmployeeName"), String)
End If

Obviously, without a bit of optimization, this second approach is slower because it requires two dictionary lookups, so what you really need is a temporary variable. Then you can use TryCast:

Dim tmp As String = TryCast(e.Values("EmployeeName"), String)
If tmp IsNot Nothing Then
  child.EmployeeName = tmp
End If

Copyright (c) Marimer LLC