Correct use of casting and DataBinder.Eval

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sphengle
    New Member
    • Oct 2008
    • 3

    Correct use of casting and DataBinder.Eval

    It’s Friday afternoon and I’m being driven mad by a simple .NET problem. Can you help?


    I’m binding in a repeater where I know there’s a possibility that the value for a field in a dataset could be null. The field is an integer.

    So in ItemDataBound I’m doing this...

    Int? myInt = (int?)DataBinde r.Eval( Container.DataI tem, “myIntField”);

    This comes up with an invalid cast exception, as does this...

    Int myInt = (int)DataBinder .Eval( Container.DataI tem, “myIntField”);


    My cop out is to do this....

    String strTemp = DataBinder.Eval ( Container.DataI tem, “myIntField”, “{0}” ); // this returns a string

    myInt = (strTemp != string.empty) ? Int.Parse( strTemp ) : 0; // or variations on this using Convert or Int.TryParse


    There has to be a simpler way?

    Sphengle
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Since the DataBinder.Eval Method evaluates data-binding expressions at run time you will get an ArgumentNullExc eption if the value is null (or nothing).

    You're going to have to do what you have outlined above: determine if the value is null, then set it to a default value if it is null before you use the DataBinder.Eval method.

    -Frinny

    Comment

    • sphengle
      New Member
      • Oct 2008
      • 3

      #3
      Hi Frinny

      Do you know if there is a way of testing for null without having to format to a string first?

      Sphengle

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        Originally posted by sphengle
        Hi Frinny

        Do you know if there is a way of testing for null without having to format to a string first?

        Sphengle
        You can use the String class's static method String.IsNullOr Empty to check if a string is null or empty. Note that if the string contains a space, it is not null or empty...so check if it's null or empty first, then trim the string and check it again if you consider space empty as well.

        -Frinny

        Comment

        Working...