Casting DBNull in Raddatepicker in Grid

2 posts, 0 answers
  1. Hafizul Fadhli
    Hafizul Fadhli avatar
    1 posts
    Member since:
    Aug 2018

    Posted 15 Aug 2018 Link to this post

    <telerik:GridTemplateColumn HeaderText="Tarikh Luput" HeaderStyle-HorizontalAlign="Center" UniqueName="ExpDate">
                                            <HeaderStyle Width="100px" />
                                                <telerik:RadDatePicker ID="dtExp" runat="server" AutoPostBack="true" OnSelectedDateChanged="dtExp_TextChanged"
                                                    DBSelectedDate='<%# IIf(IsDBNull(Eval("EXPIRY_DATE")), Nothing, Convert.ToDateTime(Eval("EXPIRY_DATE")))%>'>
                                                            runat="server" >


    It returns "Object cannot be cast from DBNull to other types." error. Help?

  2. Tsvetomir
    Tsvetomir avatar
    835 posts

    Posted 20 Aug 2018 Link to this post

    Hi Hafizul,

    The RadGrid control is capable of handling null values by default, so it is not needed to use a conditional data binding and explicit converting. You can use the following: 

    DbSelectedDate='<%# Eval("EXPIRY_DATE") %>'

    Additionally, when using VB.NET it is recommended to use IF instead of IIF, since the IIF function is executed for each part of the statement. You can find more information in the IF vs IIF MSDN forum post. Moreover, Nothing is used to specify that the variable's reference is not pointing to anything, while DBNull.Value is an object used to point out that the value coming from the DataBase is null.

    If you want to keep using the conditional binding approach, the DBSelectedDate property should look like this:
    DBSelectedDate='<%# If(IsDBNull(Eval("OrderDate")), DBNull.Value, Eval("OrderDate"))%>'

    In general, we recommend that you take advantage of the built-in features of controls, so in this case you can skip the condition for the DBSelectedValue.

    Kind regards,
    Progress Telerik
    Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Back to Top