Fileupload inside grid

hello i have this code and i want to add inside a grid a picture upload .
I used the sample form http://www.aspsnippets.com/Articles/Display-Images-in-GridView-Control-using-the-path-stored-in-SQL-Server-database.aspx and i get the error FileUpload1 not declared so i added something like  Dim FileUpload1 As FileUpload = CType(RadGrid1.FindControl("FileUpload1"), FileUpload) don't know if ok but the error disapear.
Now i get this error when i click the upload btn :
 Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 15:         Dim FileUpload1 As FileUpload = CType(RadGrid1.FindControl("FileUpload1"), FileUpload)
Line 16:
Line 17:         Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Line 18:
Line 19:         'Save files to disk
How to solve the problem?
products.aspx:
<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="products.aspx.vb" Inherits="products" title="Products Management" %>
<%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">


   
    <div>
    
        <asp:SqlDataSource ID="BrandDTS" runat="server" 
            ConnectionString="<%$ ConnectionStrings:sunglassesConnectionString %>" 
            SelectCommand="SELECT [id], [brand] FROM [brands]"></asp:SqlDataSource>
             
             <asp:SqlDataSource ID="GenderDTS" runat="server" 
            ConnectionString="<%$ ConnectionStrings:sunglassesConnectionString %>" 
            SelectCommand="SELECT [id], [gender] FROM [genders]"></asp:SqlDataSource>
    <asp:SqlDataSource ID="TypeDTS" runat="server" 
            ConnectionString="<%$ ConnectionStrings:sunglassesConnectionString %>" 
            SelectCommand="SELECT [id], [types] FROM [types]"></asp:SqlDataSource>
            <asp:SqlDataSource ID="frameDTS" runat="server" 
            ConnectionString="<%$ ConnectionStrings:sunglassesConnectionString %>" 
            SelectCommand="SELECT [id], [frame] FROM [frames]"></asp:SqlDataSource>
        <asp:SqlDataSource ID="productDTS" runat="server" 
            ConnectionString="<%$ ConnectionStrings:sunglassesConnectionString %>" 
            DeleteCommand="DELETE FROM [products] WHERE [id] = @id" 
            InsertCommand="INSERT INTO [products] ([model], [brandid], [gender], [frame], [code], [type], [new]) VALUES (@model, @brandid, @gender, @frame, @code, @type, @new)" 
            SelectCommand="SELECT * FROM [products]" 
            UpdateCommand="UPDATE [products] SET [model] = @model, [brandid] = @brandid, [gender] = @gender, [frame] = @frame, [code] = @code, [type] = @type, [new] = @new WHERE [id] = @id">
            <DeleteParameters>
                <asp:Parameter Name="id" Type="Int32" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="model" Type="String" />
                <asp:Parameter Name="brandid" Type="Int32" />
                <asp:Parameter Name="gender" Type="Int32" />
                <asp:Parameter Name="frame" Type="Int32" />
                <asp:Parameter Name="code" Type="String" />
                <asp:Parameter Name="type" Type="Int32" />
                <asp:Parameter Name="new" Type="Boolean" />
                <asp:Parameter Name="id" Type="Int32" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="model" Type="String" />
                <asp:Parameter Name="brandid" Type="Int32" />
                <asp:Parameter Name="gender" Type="Int32" />
                <asp:Parameter Name="frame" Type="Int32" />
                <asp:Parameter Name="code" Type="String" />
                <asp:Parameter Name="type" Type="Int32" />
                <asp:Parameter Name="new" Type="Boolean" />
            </InsertParameters>
        </asp:SqlDataSource>
    
        <asp:SqlDataSource ID="ColorDTS" runat="server" 
            ConnectionString="<%$ ConnectionStrings:sunglassesConnectionString %>" 
            DeleteCommand="DELETE FROM colors WHERE (id = @id)" 
            InsertCommand="INSERT INTO [colors] ([prodid], [color], [frame], [price], [foto], [discountinued]) VALUES (@prodid, @color, @frame, @price, @foto, @discountinued)" 
            SelectCommand="SELECT * FROM [colors] WHERE ([prodid] = @prodid)" 
            UpdateCommand="UPDATE [colors] SET [prodid] = @prodid, [color] = @color, [frame] = @frame, [price] = @price, [foto] = @foto, [discountinued] = @discountinued WHERE [id] = @id">
            <SelectParameters>
                <asp:Parameter Name="prodid" Type="Int32" />
            </SelectParameters>
            <DeleteParameters>
                <asp:Parameter Name="prodid" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="prodid" Type="Int32" />
                <asp:Parameter Name="color" Type="String" />
                <asp:Parameter Name="frame" Type="String" />
                <asp:Parameter Name="price" Type="Decimal" />
                <asp:Parameter Name="foto" Type="String" />
                <asp:Parameter Name="discountinued" Type="Boolean" />
                <asp:Parameter Name="id" Type="Int32" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="prodid" Type="Int32" />
                <asp:Parameter Name="color" Type="String" />
                <asp:Parameter Name="frame" Type="String" />
                <asp:Parameter Name="price" Type="Decimal" />
                <asp:Parameter Name="foto" Type="String" />
                <asp:Parameter Name="discountinued" Type="Boolean" />
            </InsertParameters>
        </asp:SqlDataSource>
        <br />
       
      
        <telerik:RadGrid ID="RadGrid1" runat="server" AllowAutomaticDeletes="True" 
            AllowAutomaticInserts="True" AllowAutomaticUpdates="True" 
            AllowFilteringByColumn="True" AllowPaging="True" AllowSorting="True" 
            AutoGenerateColumns="False" AutoGenerateDeleteColumn="True" 
            AutoGenerateEditColumn="True" DataSourceID="productDTS" GridLines="None" 
            ShowGroupPanel="True">
<MasterTableView CommandItemDisplay="TopAndBottom" DataKeyNames="id" 
                DataSourceID="productDTS" EditMode="InPlace">
<RowIndicatorColumn>
<HeaderStyle Width="20px"></HeaderStyle>
</RowIndicatorColumn>

    <DetailTables>
        <telerik:GridTableView runat="server" 
            AllowFilteringByColumn="False" CommandItemDisplay="Top" DataKeyNames="id" 
            DataSourceID="ColorDTS" EditMode="InPlace" GridLines="Horizontal">
            <ParentTableRelation>
                <telerik:GridRelationFields DetailKeyField="prodid" MasterKeyField="id" />
            </ParentTableRelation>
            <Columns>
                <telerik:GridBoundColumn AllowFiltering="False" AllowSorting="False" 
                    DataField="prodid" Display="False" UniqueName="prodid">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn AllowFiltering="False" ColumnEditorID="id" 
                    DataField="Color" DefaultInsertValue="" HeaderText="Color" UniqueName="Color">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn AllowFiltering="False" DataField="Frame" 
                    DefaultInsertValue="" HeaderText="Frame" UniqueName="Frame">
                </telerik:GridBoundColumn>
                
                <telerik:GridBoundColumn AllowFiltering="False" DataField="Price" 
                    DataType="System.Double" DefaultInsertValue="" HeaderText="Price" 
                    UniqueName="Price">
                </telerik:GridBoundColumn>
                
                 <telerik:GridCheckBoxColumn
 UniqueName="discountinued"
 HeaderText="Discountinued"
 DataField="discountinued"
 AllowSorting="true" AllowFiltering="False" DataType="System.Boolean" 
                    SortExpression="discountinued" >
</telerik:GridCheckBoxColumn> 
                <telerik:GridTemplateColumn DataField="foto" DefaultInsertValue="" 
                    HeaderText="foto" UniqueName="foto">
                   
    <ItemTemplate>
        <asp:FileUpload ID="FileUpload1" runat="server"/>
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
    </ItemTemplate>

                </telerik:GridTemplateColumn>
            </Columns>
            <EditFormSettings CaptionDataField="id">
            </EditFormSettings>
        </telerik:GridTableView>
    </DetailTables>
    <NoRecordsTemplate>
        No Products found?!
    </NoRecordsTemplate>
    <ExpandCollapseColumn Visible="True">
    </ExpandCollapseColumn>
    <Columns>
        <telerik:GridBoundColumn DataField="id" DataType="System.Int32" HeaderText="id" 
            ReadOnly="True" SortExpression="id" 
            UniqueName="id">
        </telerik:GridBoundColumn>
        <telerik:GridDropDownColumn DataField="brandid" DataSourceID="BrandDTS" 
            ListTextField="Brand" ListValueField="ID" 
            UniqueName="Brand" 
            SortExpression="brandid" DataType="System.Int32" HeaderText="Brand">
        </telerik:GridDropDownColumn>
        <telerik:GridBoundColumn DataField="Model" 
            HeaderText="Model" SortExpression="model" UniqueName="brandid">
        </telerik:GridBoundColumn>
        <telerik:GridDropDownColumn DataField="frame" DataSourceID="frameDTS" 
            DataType="System.Int32" HeaderText="Frame" 
            ListTextField="frame" ListValueField="id" SortExpression="Frame" 
            UniqueName="column2">
        </telerik:GridDropDownColumn>
        <telerik:GridDropDownColumn DataField="Gender" DataType="System.Int32" 
            HeaderText="Gender" UniqueName="column" 
            DataSourceID="GenderDTS" ListTextField="Gender" ListValueField="id" 
            SortExpression="Gender">
        </telerik:GridDropDownColumn>
        <telerik:GridDropDownColumn DataField="type" DataSourceID="TypeDTS" 
            DataType="System.Int32" HeaderText="Type" 
            ListTextField="types" ListValueField="id" UniqueName="column1" 
            SortExpression="type">
        </telerik:GridDropDownColumn>
        <telerik:GridCheckBoxColumn DataField="new" DataType="System.Boolean" 
            HeaderText="new" SortExpression="new" UniqueName="new">
        </telerik:GridCheckBoxColumn>
    </Columns>
</MasterTableView>
            <ClientSettings AllowColumnsReorder="True" AllowDragToGroup="True">
                <Selecting AllowRowSelect="True" />
                <Scrolling AllowScroll="True" UseStaticHeaders="True" />
            </ClientSettings>
        </telerik:RadGrid>
    
    </div>
   


</asp:Content>

Products.aspx.vb:

Imports System.Data
Imports System.Data.SqlClient
Imports System.IO

Partial Class products
    Inherits System.Web.UI.Page
   
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If User.Identity.IsAuthenticated = False Then
            Server.Transfer("login.aspx")
        End If
    End Sub

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim FileUpload1 As FileUpload = CType(RadGrid1.FindControl("FileUpload1"), FileUpload)
        If FileUpload1.PostedFile IsNot Nothing Then
            Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)

            'Save files to disk 
            FileUpload1.SaveAs(Server.MapPath("prodfoto/" & FileName))

            'Add Entry to DataBase 
            Dim strConnString As [String] = System.Configuration.ConfigurationManager.ConnectionStrings("sunglassesConnectionString").ConnectionString
            Dim con As New SqlConnection(strConnString)
            Dim strQuery As String = "insert into colors (foto) values(@FileName)"
            Dim cmd As New SqlCommand(strQuery)
            cmd.Parameters.AddWithValue("@FileName", FileName)
            'cmd.Parameters.AddWithValue("@FilePath", "prodfoto/" & FileName)
            cmd.CommandType = CommandType.Text
            cmd.Connection = con
            Try
                con.Open()
                cmd.ExecuteNonQuery()
            Catch ex As Exception
                Response.Write(ex.Message)
            Finally
                con.Close()
                con.Dispose()
            End Try
        End If
    End Sub


End Class

Open in new window

SoftacidAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

masterpassCommented:
Try some thing like this

you faced the problems because the grid is in the form of rows and you will have to find the Fileupload for every row and not generally for the entire GRID
For i As Integer = 0 To RadGrid1.Items.Count - 1
Dim fp1 As FileUpload = DirectCast(RadGrid1.Items(i).FindControl("FileUpload1"), FileUpload)
Next

Open in new window

SoftacidAuthor Commented:
thank you but :
 Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: BC30451: Name 'FileUpload1' is not declared.

Source Error:

Line 17:         Next
Line 18:
Line 19:         If FileUpload1.PostedFile IsNot Nothing Then
Line 20:             Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Line 21:
SoftacidAuthor Commented:
you could see the photo
untitled.jpg
Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

masterpassCommented:
Try this

the problem is you have not declared FileUpload1 but you have declared it as fp1 .. so change it to the below code

NB: I don't know what you are trying to do .. coz if you some thing like this you will get only the content from the fileupload control in the last row of the radgrid. If you want it for every fileupload control in the grid, then write the event in the btnUpload_Click event ....

Tip: If you have AJAX enabled in your RadGrid, FileUpload control won't work. It is because the Fileupload control is a postback control and hence will require a postback and not a partial page postback
Dim FileUpload1 As FileUpload
For i As Integer = 0 To RadGrid1.Items.Count - 1
FileUpload1 = DirectCast(RadGrid1.Items(i).FindControl("FileUpload1"), FileUpload)
Next

Open in new window

SoftacidAuthor Commented:
still get after pressing the submit button Server Error in '/sunglasses2' Application.
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 19:
Line 20:
Line 21:         If FileUpload1.PostedFile IsNot Nothing Then
Line 22:             Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Line 23:
SoftacidAuthor Commented:
and the image is not uploaded
masterpassCommented:
Did you see the Note and Tip in my earlier post ? If both are not applicable to you .. try to elaborate on what you are trying to do ...
SoftacidAuthor Commented:
i just want to upload a file in a folder and add in the db foto column the name of the file uploaded that's all
SoftacidAuthor Commented:
i would like to accomplish this with radupload if possible if no with a regular upload component and i don't know how to add this in the grid
masterpassCommented:
just go through these links

http://www.telerik.com/community/forums/aspnet/upload/using-radupload-in-radgrid.aspx
(a sample application is there in this thread from telerik)

OR

http://fredrik.nsquared2.com/viewpost.aspx?PostID=292
(this is ASP GridView but you can use the idea)

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
SoftacidAuthor Commented:
thanks masterpass , i look before to the first example but because of my limited knowledge in .net .. i wasn't able to apply in my case.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.