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

Object must implement IConvertible.

5 Answers 386 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Aamir
Top achievements
Rank 1
Aamir asked on 03 Aug 2011, 08:31 AM

I am using Telerik RadControls. I have radGrid in which i have upload control for inserting images. But error is thrown when I try to upload any file.

Object must implement IConvertible.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Object must implement IConvertible.

Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidCastException: Object must implement IConvertible.] System.Convert.ChangeType(Object value, TypeCode typeCode, IFormatProvider provider) +2877013 System.Web.UI.WebControls.Parameter.GetValue(Object value, String defaultValue, TypeCode type, Boolean convertEmptyStringToNull, Boolean ignoreNullableTypeChanges) +141 System.Web.UI.WebControls.Parameter.GetValue(Object value, Boolean ignoreNullableTypeChanges) +63 System.Web.UI.WebControls.SqlDataSourceView.AddParameters(DbCommand command, ParameterCollection reference, IDictionary parameters, IDictionary exclusionList, String oldValuesParameterFormatString) +524 System.Web.UI.WebControls.SqlDataSourceView.ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues) +141 System.Web.UI.DataSourceView.Update(IDictionary keys, IDictionary values, IDictionary oldValues, DataSourceViewOperationCallback callback) +92 Telerik.Web.UI.GridTableView.PerformUpdate(GridEditableItem editedItem, Boolean suppressRebind) +224 Telerik.Web.UI.GridCommandEventArgs.ExecuteCommand(Object source) +985 Telerik.Web.UI.RadGrid.OnBubbleEvent(Object source, EventArgs e) +134 System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37 Telerik.Web.UI.GridEditFormItem.OnBubbleEvent(Object source, EventArgs e) +216 System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37 System.Web.UI.WebControls.ImageButton.OnCommand(CommandEventArgs e) +111 System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +176 System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565


I am actually trying to use this example with my databases and all.

http://demos.telerik.com/aspnet-ajax/controls/examples/integration/raduploadinajaxifiedgrid/defaultvb.aspx?product=grid&RadUrid=2ecccfe5-76bd-4310-b0a3-c5c84afc1beb



5 Answers, 1 is accepted

Sort by
0
Aamir
Top achievements
Rank 1
answered on 03 Aug 2011, 03:15 PM
Code Behind
===============

Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports System.IO
Imports Telerik.Web.UI
 
 
 
Namespace Telerik.Web.Examples.Ajax.Integration.RadUploadInAjaxifiedGrid
 
    Partial Class Accounts_admin_menu
        Inherits System.Web.UI.Page
 
 
        Protected Sub RadGrid1_ItemDataBound(ByVal sender As Object, ByVal e As GridItemEventArgs) Handles RadGrid1.ItemDataBound
 
            Try
 
                If TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode Then
                    Dim editItem As GridEditableItem = DirectCast(e.Item, GridEditableItem)
                    Dim upload As RadUpload = DirectCast(editItem.EditManager.GetColumnEditor("Upload"), GridBinaryImageColumnEditor).RadUploadControl
                    RadAjaxPanel1.ResponseScripts.Add(String.Format("window['UploadID'] = '{0}';", upload.ClientID))
 
                End If
            Catch ex As Exception
 
                lblStatus.Text = ex.Message
            End Try
 
 
        End Sub
 
        Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As GridItemEventArgs)
 
            Try
                If TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode Then
                    Dim editItem As GridEditableItem = DirectCast(e.Item, GridEditableItem)
                    Dim upload As RadUpload = DirectCast(editItem.EditManager.GetColumnEditor("Upload"), GridBinaryImageColumnEditor).RadUploadControl
 
                    Dim validator As CustomValidator = New CustomValidator()
                    validator.ErrorMessage = "Please select file to be uploaded"
                    validator.ClientValidationFunction = "validateRadUpload"
                    validator.Display = ValidatorDisplay.Dynamic
                    DirectCast(upload.Parent, TableCell).Controls.Add(validator)
                End If
            Catch ex As Exception
                lblStatus.Text = ex.Message
            End Try
 
             
        End Sub
 
        Protected Function TrimDescription(ByVal description As String) As String
            If Not String.IsNullOrEmpty(description) AndAlso description.Length > 200 Then
                Return String.Concat(description.Substring(0, 200), "...")
            End If
            Return description
        End Function
 
    End Class
 
End Namespace


ASPX FILE
=========
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
 
        <script type="text/javascript">
        // <![CDATA[
            //On insert and update buttons click temporarily disables ajax to perform upload actions
            function conditionalPostback(sender, eventArgs) {
                var theRegexp = new RegExp("\.UpdateButton$|\.PerformInsertButton$", "ig");
                if (eventArgs.get_eventTarget().match(theRegexp)) {
                    var upload = $find(window['productURL']);
 
                    //AJAX is disabled only if file is selected for upload
                    if (upload.getFileInputs()[0].value != "") {
                        eventArgs.set_enableAjax(false);
                    }
                }
            }
 
            function validateRadUpload(source, e) {
                e.IsValid = false;
 
                var upload = $find(source.parentNode.getElementsByTagName('div')[0].id);
                var inputs = upload.getFileInputs();
                for (var i = 0; i < inputs.length; i++) {
                    //check for empty string or invalid extension
                    if (inputs[i].value != "" && upload.isExtensionValid(inputs[i].value)) {
                        e.IsValid = true;
                        break;
                    }
                }
            }
            // ]]>
        </script>
    </telerik:RadCodeBlock>
 
 
 
   
 
    <asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>
 
 
    <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" ClientEvents-OnRequestStart="conditionalPostback">
        <telerik:RadProgressManager ID="RadProgressManager1" runat="server" />
        <telerik:RadProgressArea ID="RadProgressArea1" runat="server"/>
         
 
 
         
        <telerik:RadGrid ID="RadGrid1" runat="server" AllowAutomaticDeletes="True"
                    AllowAutomaticInserts="True" AllowAutomaticUpdates="True"
                 AllowPaging="True" DataSourceID="SqlDataSource1" AutoGenerateColumns="False"
                    Skin="Telerik" AllowSorting="True" ShowStatusBar="True" OnItemDataBound="RadGrid1_ItemDataBound" OnItemCreated="RadGrid1_ItemCreated"
            PageSize="10"
            GridLines="None">
                     
             
            <PagerStyle Mode="NumericPages" AlwaysVisible="true" />
 
            <MasterTableView CellSpacing="0" CommandItemDisplay="TopAndBottom"
                                    DataSourceID="SqlDataSource1" HorizontalAlign="NotSet"
                            AutoGenerateColumns="false" DataKeyNames="PID">
    
   
    <Columns>
 
            <telerik:GridEditCommandColumn ButtonType="ImageButton" UniqueName="EditCommandColumn">
                        <ItemStyle CssClass="MyImageButton" />
                    </telerik:GridEditCommandColumn>
        
 
        <telerik:GridBoundColumn DataField="productName"
            HeaderText="productName" SortExpression="productName"
            UniqueName="productName" ColumnEditorID="GridTextBoxColumnEditor1">
        </telerik:GridBoundColumn>
 
 
        <telerik:GridBoundColumn DataField="CID" DataType="System.Int32"
            HeaderText="CID" SortExpression="CID"
            UniqueName="CID">
        </telerik:GridBoundColumn>
        <telerik:GridBoundColumn DataField="productDescription" HeaderText="productDescription"
            SortExpression="productDescription" UniqueName="productDescription">
        </telerik:GridBoundColumn>
 
       
         
         <telerik:GridBoundColumn DataField="productPrice" DataType="System.Decimal"
             HeaderText="productPrice" SortExpression="productPrice"
             UniqueName="productPrice">
         </telerik:GridBoundColumn>
          
        <%-- <telerik:GridBoundColumn DataField="productURL" HeaderText="productURL"
             SortExpression="productURL" UniqueName="Upload">
 
         </telerik:GridBoundColumn>
--%>
 
 
         <telerik:GridBinaryImageColumn DataField="productURL" HeaderText="Image" UniqueName="Upload" ImageAlign="NotSet"
                        ImageHeight="80px" ImageWidth="80px" ResizeMode="Fit"
                        DataAlternateTextFormatString="Image of {0}">
                        <HeaderStyle Width="10%" />
                    </telerik:GridBinaryImageColumn>
        
    
    
 
                    
                    <telerik:GridButtonColumn Text="Delete" CommandName="Delete" ButtonType="ImageButton">
                        <HeaderStyle Width="2%" />
                    </telerik:GridButtonColumn>
        
               
         
 
    </Columns>
 
        <EditFormSettings>
                    <EditColumn ButtonType="ImageButton" />
                     
                    
        </EditFormSettings>
                 
                 
 
</MasterTableView>
 
<HeaderContextMenu EnableImageSprites="True" CssClass="GridContextMenu GridContextMenu_Default"></HeaderContextMenu>
                </telerik:RadGrid>
 
 
 
 
 
    </telerik:RadAjaxPanel>
 
 
 
 
 
                <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                    ConflictDetection="CompareAllValues"
                    ConnectionString="<%$ ConnectionStrings:SouzaConnectionString %>"
                    DeleteCommand="DELETE FROM [menu] WHERE [PID] = @original_PID AND [productName] = @original_productName AND [CID] = @original_CID AND (([productDescription] = @original_productDescription) OR ([productDescription] IS NULL AND @original_productDescription IS NULL)) AND (([productPrice] = @original_productPrice) OR ([productPrice] IS NULL AND @original_productPrice IS NULL)) AND (([productURL] = @original_productURL) OR ([productURL] IS NULL AND @original_productURL IS NULL))"
                    InsertCommand="INSERT INTO [menu] ([productName], [CID], [productDescription], [productPrice], [productURL]) VALUES (@productName, @CID, @productDescription, @productPrice, @productURL)"
                    OldValuesParameterFormatString="original_{0}"
                    SelectCommand="SELECT * FROM [menu]"
                     
                    UpdateCommand="UPDATE [menu] SET [productName] = @productName, [CID] = @CID, [productDescription] = @productDescription, [productPrice] = @productPrice, [productURL] = @productURL WHERE Convert(varchar(36),[PID]) = @original_PID AND [productName] = @original_productName AND [CID] = @original_CID AND (([productDescription] = @original_productDescription) OR ([productDescription] IS NULL AND @original_productDescription IS NULL)) AND (([productPrice] = @original_productPrice) OR ([productPrice] IS NULL AND @original_productPrice IS NULL)) AND (([productURL] = @original_productURL) OR ([productURL] IS NULL AND @original_productURL IS NULL))">
 
                     
         
                    <DeleteParameters>
                        <asp:Parameter Name="original_PID" DbType="Int32" />
                        <asp:Parameter Name="original_productName" DbType="String" />
                        <asp:Parameter Name="original_CID" DbType="Int32" />
                        <asp:Parameter Name="original_productDescription" DbType="String" />
                        <asp:Parameter Name="original_productPrice" DbType="Decimal" />
                        <asp:Parameter Name="original_productURL" DbType="String" />
                    </DeleteParameters>
                    <InsertParameters>
                        <asp:Parameter Name="productName" DbType="String" />
                        <asp:Parameter Name="CID" DbType="Int32" />
                        <asp:Parameter Name="productDescription" DbType="String" />
                        <asp:Parameter Name="productPrice" DbType="Decimal" />
                        <asp:Parameter Name="productURL" DbType="String" />
                    </InsertParameters>
                    <UpdateParameters>
                        <asp:Parameter Name="productName" DbType="String" />
                        <asp:Parameter Name="CID" DbType="Int32" />
                        <asp:Parameter Name="productDescription" DbType="String" />
                        <asp:Parameter Name="productPrice" DbType="Decimal" />
                        <asp:Parameter Name="productURL" DbType="String" />
                        <asp:Parameter Name="original_PID" DbType="Int32" />
                        <asp:Parameter Name="original_productName" DbType="String" />
                        <asp:Parameter Name="original_CID" DbType="Int32" />
                        <asp:Parameter Name="original_productDescription" DbType="String" />
                        <asp:Parameter Name="original_productPrice" DbType="Decimal" />
                        <asp:Parameter Name="original_productURL" DbType="String" />
 
                    </UpdateParameters>
                </asp:SqlDataSource>
 
 
 
 
   

0
Marin
Telerik team
answered on 04 Aug 2011, 02:51 PM
Hi Aamir,

 Judging by the name of the data field (productURL) bound to the GridBinaryImageColumn it looks like it is of string type stored in the database. This causes the error because the GridBinaryImageColumn uploads the actual image serialized as binary data, which fails to be converted to string. In the demo that you are following the data field for the GridbinaryImageColumn is of type image in the database. So I would recommend also using this type if you want to actually store the image in the database. Otherwise a simple GridBoundColumn or GridHyperLinkColumn can store only the link to the image.

Hope this helps.

All the best,
Marin
the Telerik team

Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

0
Aamir
Top achievements
Rank 1
answered on 04 Aug 2011, 07:28 PM
When I use GridBoundColumn I get a simple textbox in radGrid. How will I get the radUpload in it and set the saveAs and other validation for radUpload?
0
Marin
Telerik team
answered on 05 Aug 2011, 03:43 PM
Hi Aamir,

 You can use the RadUpload control and the GridBinaryImageColumn to upload images and save them only if your field in the database is of binary type (not string). If this is the case then you should have no problems in using the RadUpload and the GridBinaryImageColumn otherwise I am afraid that this is not possible.

All the best,
Marin
the Telerik team

Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

0
Aamir
Top achievements
Rank 1
answered on 06 Aug 2011, 10:35 AM
<telerik:GridTemplateColumn HeaderText="Product Image"
                       UniqueName="TemplateColumn">
                       <EditItemTemplate>
                         
                           <telerik:RadUpload ID="RadUpload1" Runat="server"
                               ControlObjectsVisibility="None" TargetPhysicalFolder="D:\PROJECTS\SouzaLobo\Images">
                           </telerik:RadUpload>
                            
                       </EditItemTemplate>
                       
                        
                   </telerik:GridTemplateColumn>

I have put the radUpload in the GridTemplateColumn and now I can upload the files but I need to store the url in the database table.
How can I bind the uploaded file path to 'productURL' in table.
Tags
Grid
Asked by
Aamir
Top achievements
Rank 1
Answers by
Aamir
Top achievements
Rank 1
Marin
Telerik team
Share this question
or