quinta-feira, 22 de setembro de 2011

ASP.NET C# Eval int null

Earlier this day, I've came across this issue with Evaluating nullable ints. So I have:


  • A Custom User Control (A);
  • A Repeater of A;
So I was trying to do something lilke this:

<asp:Repeater ID="rA" runat="server" OnItemCommand="rAHandler">
     <ItemTemplate>
          <tr align="center">
               <td>
                    <uc1:UC_A ID="UC_A" runat="server" value='<%#Eval("value") %>'  />
                    ...

So that when the page loads, every existing control in the repeater can be properly displayed and binded with values from the database.

The big issue here, is that value is represented as a nullable int in the database, so if the value is in fact null, the Eval method throws an exception..

Best way I figured after a couple of hours trying to understand if there was something wrong with the tableadapter, was a simple method used to Pre-Evaluate the Eval:

protected int? EvalCheck(object obj)
{
     if (object.ReferenceEquals(obj, DBNull.Value))
     {
          return null;
     }
     else
     {
          return (int?)obj;
     }
}

And in the repeater:

                    <uc1:UC_A ID="UC_A" runat="server" value='<%#EvalCheck(Eval("value")) %>'  />


That's it! = )