This is a migrated thread and some comments may be shown as answers.

Edit and Insert Binding.

1 Answer 79 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Neil
Top achievements
Rank 1
Neil asked on 30 Jan 2012, 10:39 PM

I am having issues when using an edit template to create a new record. On insert, the same binding is assumed and does not work as there is nothng to bind to. For example, I have a date picker for which I have resricted the range from 2011 to 2050. On insert, there is no value being passed in and so an exception raised (Object cannot be cast from DBNull to other types.)
e.g.

<td>

 <asp:CheckBox ID="Critical_E" runat="server" Text="Critical" Checked='<%# DataBinder.Eval( Container, "DataItem.Critical" ) %>' />

 </td>


How do I either 1) disable the binding on insert, 2) create a separate insert template without having to create user controls?

Thanks,

Neil.

1 Answer, 1 is accepted

Sort by
0
Veli
Telerik team
answered on 02 Feb 2012, 12:25 PM
Hi Neil,

You can simply have a server-side method that can do the databinding for you. If you make that method generic, with the generic type argument being the result type, you can use it with DBNull values without getting invalid cast exceptions. Here is an example:

protected T BindTo<T>(object container, string expression)
{
    try
    {
        return (T)DataBinder.Eval(container, expression);
    }
    catch (InvalidCastException e)
    {
        return default(T);
    }
}

You can now use BindTo to bind a boolean field that can potentially have DBNull values:

<asp:CheckBox ID="Critical_E" runat="server" Text="Critical" Checked='<%# BindTo<bool>(Container, "DataItem.Critical" ) %>' />


Veli
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
Tags
Grid
Asked by
Neil
Top achievements
Rank 1
Answers by
Veli
Telerik team
Share this question
or