locked
Access File from Upload Control in RowCommand in VB (From a GridView) RRS feed

  • Question

  • User-1822443940 posted

    I'm having a lot of frustration implementing this and can't seem to find any good answers (or at least none in VB). I'm not really good at translating C# to VB, and I didn't see my answer from the stick note in this section (https://weblogs.asp.net/davidfowler/getting-your-data-out-of-the-data-controls). With that said...

    WHAT I'M TRYING TO ACCOMPLISH

    I have a gridview named gvALL_ACCESS. For each row in this gridview, I have an upload control and then a button (in the same column). I would like the button to call a command via the gvALL_ACCESS_RowCommand() function that will take the information (the file) from the upload control and upload it to a database.

    WHAT'S NOT WORKING

    I'm having trouble figuring out how to access the file data from within the gvALL_ACCESS_RowCommand() function. Specifically, I need to get the file in such a way that I can assign it to a stream datalike this:

    Using fs As Stream = My.File.Data

    MY CODE SO FAR

    ASPX

    <asp:GridView ID="gvALL_ACCESS" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDs_ALL_ACCESS"
    	 OnRowCommand="gvALL_ACCESS_RowCommand" AllowSorting="True">
    	<AlternatingRowStyle BackColor="LightGray" HorizontalAlign="Left" />
    	<EditRowStyle HorizontalAlign="Left" />
    	<RowStyle HorizontalAlign="Left" />
    	<Columns>
    		<asp:BoundField ControlStyle-Width="150" DataField="USERID" HeaderText="USERID" SortExpression="USERID" >
    		<ControlStyle Width="150px" />
    		</asp:BoundField>
    		<asp:BoundField ControlStyle-Width="200" DataField="FULLNAME" HeaderText="NAME" SortExpression="FULLNAME" ReadOnly="true" >
    		<ControlStyle Width="200px" />
    		</asp:BoundField>
    		<asp:TemplateField HeaderText="COL FILE">
    			<ItemTemplate>
    				<asp:FileUpload ID="FileUpload1" runat="server" />
    				<asp:Button CommandName="UploadCOLFile" Text="Upload" runat="server"/>
    			</ItemTemplate>
    		</asp:TemplateField>
    	</Columns>
    </asp:GridView>

    Code Behind

    Protected Sub gvALL_ACCESS_RowCommand(sender As Object, e As GridViewCommandEventArgs)
    
    	Dim rowIndex As Integer = Convert.ToInt32(e.CommandArgument)
    	Dim row As GridViewRow = gvALL_ACCESS.Rows(rowIndex)
    
    	If e.CommandName = "UploadCOLFile" Then
    		FileUpload fu = row.Cells(2).FindControl("FileUpload1")
    		Using fs As Stream = fu
    	End If
    
    End Sub

    WHAT I'VE ATTEMPTED

    The closest thing I've found so far that does what I'm trying to do is this link: https://www.aspsnippets.com/Articles/Read-and-Write-BLOB-Data-to-SQL-Server-database-using-C-and-VBNet.aspx

    Unfortunately, this upload control is outside of the GridView. Other than that, if I can get the file from within the gridview, I could use the code!

    This link was also really close (and even in VB), but it's for a TextBox, and I need some kind of filetype I can read from: https://forums.asp.net/t/1379819.aspx?getting+values+from+controls+in+gridview+rows

    Again, here's a link from Microsoft, but it doesn't show how to deal with the FileUpload: https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.gridview.rowcommand?view=netframework-4.7.2

    Unfortunately, I just can't seem to figure out the right code to get my file in a variable to be read as a stream. What can I do to accomplish this? Thanks in advance for any help!!!

    Thursday, December 13, 2018 5:31 PM

All replies

  • User-1174608757 posted

    Hi Nightmare637

     According to your description,I have made a sample here,you could use row.FindControl( ) to get the FileUpload Control firstly, then you can use PostedFile.InputStream to

    convert the file you selected to stream and use BinaryReader to convert stream to bytes.Finally you can save the bytes to Database. Here is the code ,I hope it will help you.

    fileup.aspx:

    <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="fileup.aspx.vb" Inherits="VBWeb.fileup" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" Height="255px" Width="584px">
                   <Columns>
                       <asp:TemplateField>
                           <ItemTemplate>
                          <asp:FileUpload ID="FileUpload1" runat="server" />
             <asp:Button CommandName="UploadCOLFile" CommandArgument='<%# Eval("id") %>' Text="Upload" runat="server"/>
                           </ItemTemplate>
                       </asp:TemplateField>
                   </Columns>
                </asp:GridView>
            </div>
        </form>
    </body>
    </html>

    fileup.aspx.vb:

    Imports System.Data.SqlClient
    Imports System.IO
    
    Public Class fileup
        Inherits System.Web.UI.Page
        Public Shared Function ExecuteDataTable(ByVal sql As String, ParamArray pms As SqlParameter()) As DataTable
            Dim conStr As String = ConfigurationManager.ConnectionStrings("mssqlserver").ConnectionString
            Dim dt As DataTable = New DataTable()
    
            Using adapter As SqlDataAdapter = New SqlDataAdapter(sql, conStr)
    
                If pms IsNot Nothing Then
                    adapter.SelectCommand.Parameters.AddRange(pms)
                End If
    
                adapter.Fill(dt)
            End Using
    
            Return dt
        End Function
        Public Shared Function ExecuteNonQuery(ByVal sql As String, ParamArray pms As SqlParameter()) As Integer
            Dim conStr As String = ConfigurationManager.ConnectionStrings("mssqlserver").ConnectionString
            Using con As SqlConnection = New SqlConnection(conStr)
    
                Using cmd As SqlCommand = New SqlCommand(sql, con)
    
                    If pms IsNot Nothing Then
                        cmd.Parameters.AddRange(pms)
                    End If
    
                    con.Open()
                    Return cmd.ExecuteNonQuery()
                End Using
            End Using
        End Function
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
            If Not IsPostBack Then
                Dim s As String = "select * from Fight"
                Me.GridView1.DataSource = ExecuteDataTable(s)
                Me.GridView1.DataBind()
            End If
        End Sub
    
        Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
            If e.CommandName = "UploadCOLFile" Then
                Dim id As String = e.CommandArgument.ToString()
                Dim row As GridViewRow = CType(((CType(e.CommandSource, Control)).NamingContainer), GridViewRow)
                Dim fp As FileUpload = TryCast(row.FindControl("FileUpload1"), FileUpload)
    
                Using fs As Stream = fp.PostedFile.InputStream
    
                    Using br As BinaryReader = New BinaryReader(fs)
                        Dim bytes As Byte() = br.ReadBytes(CType(fs.Length, Int32))
                        Dim sql As String = "update Fight set data=@bytes where id =@id"
                        Dim prms As SqlParameter() = {New SqlParameter("@bytes", bytes), New SqlParameter("@id", id)}
                        Dim a As Integer = CInt(ExecuteNonQuery(sql, prms))
    
                        If a > 0 Then
                            Response.Write("Insert Successfully")
                        End If
                    End Using
                End Using
            End If
        End Sub
    
    End Class
    

    Best Regards

    WeiZhang

    Friday, December 14, 2018 8:03 AM
  • User-1822443940 posted

    Thank you so much for the reply! I feel like I'm so close to the answer too!!! I'm now having an issue with the Stream portion, though. When I try this line of code:

    Using fs As Stream = fp.PostedFile.InputStream

    I keep getting an error that says 'PostedFile' is not a member of 'FileUpload'. I can't seem to figure out why this is happening... Any idea why?

    Friday, December 14, 2018 2:26 PM
  • User-1174608757 posted

    Hi Nightmare637

      According to your description, the  'PostedFile' is  based on  ASP.Net 4.5 and hence you will need to upgrade to ASP.Net 4.5. If you still have this problem , could you please 

    post more details about your code?It will help me solve your problem.

     Best Regards

    Wei Zhang 

    Monday, December 17, 2018 1:27 AM
  • User-1822443940 posted

    Thank you again for your response. I checked the framework by right clicking on the Project, clicking Properties, and then looking at the Target framework. It said the target framework was .NET Framework 4.5 in the Application section. I tried changing the framework to 4.6.1, but this did not seem to change anything either.

    In Web.config, the compilation and httpRuntime both reflected 4.5 as well.

    Could there be perhaps be something I'm not considering here with the framework?

    Wednesday, January 2, 2019 8:02 PM
  • User-1174608757 posted

    Hi Nightmare637

    I have searched a lot about your situation. I suggest  you to write as below.I think it will work ,if you still have problem, I wish you could post details about your code .I will try my best to figure it out.

    <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />

    Here is the link ,I hope it can help you.

    https://www.aspforums.net/Threads/156158/ASPNet-error-PostedFiles-is-not-a-member-of-SystemWebUIWebControlsFileUpload/

    https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.fileupload.postedfile?view=netframework-4.7.2

    https://stackoverflow.com/questions/23471350/fileupload-contol-not-showing-posted-files

    Best Regards

    Wei Zhang

    Thursday, January 3, 2019 6:00 AM
  • User-1822443940 posted

    Thanks again for your post. The solution you posted did not work for me, but I was able to dig down a bit deeper and I think I am starting to see the problem. I noticed that in certain parts of the page, if I added a control such as a button, label, text box, etc., then in the designer.vb file, these controls would also be added. However, in other parts of the page, the corresponding designer.vb would NOT be updated.

    Specifically, I noticed this trend: if the control was inside a ListView, FormView, or GridView, then the definition would not be added to the designer.vb file. By playing around with the code, I also noticed that if the control was added into the designer.vb file, then I had no issues using the FileUpload.PostedFile property. 

    I tried adding the FileUpload control to a FormView, and couldn't get it to work. However, I noticed something else: my code was inside a Panel tag (NOT an update Panel tag). I saw there were some issues with this from googling, so I'm wondering if this might be the case. Anyways, here is more of my code. Please let me know if there is something I'm missing!

    ASPX

    <%@ Page Title="Upload File Page" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Admin.aspx.vb" Inherits="UploadFilePage.Admin" Trace="false" %>
    <asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <article>
    <asp:Panel ID="pnlAdminAccess" runat="server" BackColor="#CCFFFF" Visible="false">
    <asp:GridView
    ID="gvALL_ACCESS" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDs_ALL_ACCESS" OnRowCommand="gvALL_ACCESS_RowCommand" AllowSorting="True"> <AlternatingRowStyle BackColor="LightGray" HorizontalAlign="Left" /> <EditRowStyle HorizontalAlign="Left" /> <RowStyle HorizontalAlign="Left" /> <Columns> <asp:BoundField ControlStyle-Width="150" DataField="USERID" HeaderText="USERID" SortExpression="USERID" > <ControlStyle Width="150px" /> </asp:BoundField> <asp:BoundField ControlStyle-Width="200" DataField="FULLNAME" HeaderText="NAME" SortExpression="FULLNAME" ReadOnly="true" > <ControlStyle Width="200px" /> </asp:BoundField> <asp:TemplateField HeaderText="COL FILE"> <ItemTemplate> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button CommandName="UploadCOLFile" Text="Upload" runat="server"/> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
    </asp:Panel>
    </article>
    </asp:Content>

    Monday, January 7, 2019 5:38 PM