So I'm uploading multiple images to a folder and inserting the images information to a database. The upload and insert is working great but the loop is running twice for each file and adding the information into the databse twice. I am unsure as to why this is happening. Please help. Here is my code.

Protected Sub btnUploadAll_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUploadAll.Click

    If Session("RefNO") = "" Then

        generateRefNo()

    End If

    Dim myConnection As SqlConnection = New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
    Dim myCommand As SqlCommand = New SqlCommand("Insert_Stud_Stock_Images", myConnection)
    ' Mark the Command as a SPROC
    myCommand.CommandType = CommandType.StoredProcedure
    ' Add Parameters to SPROC

    Try
        ' Get the HttpFileCollection
        Dim hfc As HttpFileCollection = Request.Files

        For i As Integer = 0 To hfc.Count - 1
            Dim hpf As HttpPostedFile = hfc(i)
            If hpf.ContentLength > 0 Then

                hpf.SaveAs(Server.MapPath("images\StudStock") & "\" & System.IO.Path.GetFileName(hpf.FileName))

                '@ImageName varchar(25)
                Dim parameterImageName As SqlParameter = New SqlParameter("@ImageName", SqlDbType.VarChar, 100)
                parameterImageName.Value = hpf.FileName
                myCommand.Parameters.Add(parameterImageName)

                '@ImageSize varchar(25)
                Dim parameterImageSize As SqlParameter = New SqlParameter("@ImageSize", SqlDbType.VarChar, 100)
                parameterImageSize.Value = hpf.ContentLength
                myCommand.Parameters.Add(parameterImageSize)

                '@ImageType varchar(25)
                Dim parameterImageType As SqlParameter = New SqlParameter("@ImageType", SqlDbType.VarChar, 100)
                parameterImageType.Value = hpf.ContentType
                myCommand.Parameters.Add(parameterImageType)

                '@RefNo varchar(25)
                Dim parameterRefNo As SqlParameter = New SqlParameter("@RefNo", SqlDbType.VarChar, 25)
                parameterRefNo.Value = Session("RefNO")
                myCommand.Parameters.Add(parameterRefNo)


                'Response.Write("File: " & hpf.FileName & " Size: " & hpf.ContentLength & " Type: " & hpf.ContentType & " Uploaded Successfully <br>")

                Try
                    myConnection.Open()
                Catch ex As Exception
                    lblStatusAll.Text = ex.ToString
                End Try

                Try
                    myCommand.ExecuteNonQuery()
                Catch ex As Exception
                    lblStatusAll1.Text = ex.ToString
                End Try

                Try
                    myConnection.Close()
                Catch ex As Exception
                    lblStatusAll2.Text = ex.ToString
                End Try


            End If
        Next i
    Catch ex As Exception
        lblStatusAll3.Text = ex.ToString
    End Try
End Sub

Say if I upload 3 images it inserts this into the database:

    MackayQLD.png   103398  image/x-png     766146647560
    NorthernQLD.png 103678  image/x-png     766146647560
    SouthWestQLD.png    104579  image/x-png     766146647560
    MackayQLD.png   103398  image/x-png     766146647560
    NorthernQLD.png 103678  image/x-png     766146647560
    SouthWestQLD.png    104579  image/x-png     766146647560

I only want it to insert the information once for each image.

I have also changed the code to this:

Protected Sub btnUploadAll_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUploadAll.Click

        If Session("RefNO") = "" Then

            generateRefNo()

        End If

        Try
            ' Get the HttpFileCollection
            Dim hfc As HttpFileCollection = Request.Files

            For i As Integer = 0 To hfc.Count - 1
                Dim hpf As HttpPostedFile = hfc(i)
                If hpf.ContentLength > 0 Then

                    hpf.SaveAs(Server.MapPath("images\StudStock") & "\" & System.IO.Path.GetFileName(hpf.FileName))

                    Dim myConnection As SqlConnection = New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
                    Dim myCommand As SqlCommand = New SqlCommand("Insert_Stud_Stock_Images", myConnection)
                    ' Mark the Command as a SPROC
                    myCommand.CommandType = CommandType.StoredProcedure
                    ' Add Parameters to SPROC

                    '@ImageName varchar(25)
                    Dim parameterImageName As SqlParameter = New SqlParameter("@ImageName", SqlDbType.VarChar, 100)
                    parameterImageName.Value = hpf.FileName
                    myCommand.Parameters.Add(parameterImageName)

                    '@ImageSize varchar(25)
                    Dim parameterImageSize As SqlParameter = New SqlParameter("@ImageSize", SqlDbType.VarChar, 100)
                    parameterImageSize.Value = hpf.ContentLength
                    myCommand.Parameters.Add(parameterImageSize)

                    '@ImageType varchar(25)
                    Dim parameterImageType As SqlParameter = New SqlParameter("@ImageType", SqlDbType.VarChar, 100)
                    parameterImageType.Value = hpf.ContentType
                    myCommand.Parameters.Add(parameterImageType)

                    '@RefNo varchar(25)
                    Dim parameterRefNo As SqlParameter = New SqlParameter("@RefNo", SqlDbType.VarChar, 25)
                    parameterRefNo.Value = Session("RefNO")
                    myCommand.Parameters.Add(parameterRefNo)


                    Try
                        myConnection.Open()
                    Catch ex As Exception
                        lblStatusAll.Text = ex.ToString
                    End Try

                    Try
                        myCommand.ExecuteNonQuery()
                    Catch ex As Exception
                        lblStatusAll1.Text = ex.ToString
                    End Try

                    Try
                        myConnection.Close()
                    Catch ex As Exception
                        lblStatusAll2.Text = ex.ToString
                    End Try


                End If
            Next i
        Catch ex As Exception
            lblStatusAll3.Text = ex.ToString
        End Try
    End Sub

How many FileUpload controls are there in your markup? If it is single then no need to add database code in a loop. Please post markup (.aspx).

I have two FileUpload controls. One to upload a PDF and the other to upload the images. Both are inside a form to upload information to a database

Here's the .aspx page. There is a lot on that page so I have only included the code about the FileUpload controls:

  <tr>
    <td align="left" colspan="4" style="height: 25px">
    <asp:Label ID="Label29" runat="server" Font-Bold="True" Font-Names="Calibri" Font-Size="11pt"
      Text="Upload catalogue as a PDF ..." Width="320px"></asp:Label></td>
  </tr>
  <tr>
    <td align="left" height="5" style="width: 16%">
    <asp:Label ID="Label30" runat="server" Text="PDF to Upload:" Width="135px" Font-Bold="False" Font-Names="Calibri" Font-Size="11pt"></asp:Label>
    </td>
    <td align="left" colspan="3" width="90%">
    <asp:FileUpload ID="PDFFileUpload" runat="server" Font-Names="Calibri" Font-Size="11pt" Width="90%" />
    </td>
  </tr>
  <tr>
    <td align="left" height="5" style="width: 16%">
    </td>
    <td align="left" colspan="3" width="90%">
    <asp:Button ID="btnUploadfilePDF" runat="server" Font-Names="Calibri" Font-Size="10.5pt" OnClick="btnUploadfilePDF_Click" Text="Upload & Save " Width="115px" />
    <span style =" font-size :11pt; color :Red ; font-family :Calibri " >(Max. 10 Mb)</span></td>
  </tr>
  <tr>
    <td align="center" colspan="4" height="5">
    <asp:Label ID="lblStatus" runat="server" Font-Names="Calibri" Font-Size="11pt" ForeColor="#C00000"
      Visible="False" Width="401px"></asp:Label></td>
  </tr>


  <tr>
    <td width="10%" height="5" align="left">
    </td>
    <td width="90%" colspan="3" align="left">
    </td>
  </tr>

  <tr>
      <td align="left" colspan="4" style="height: 25px">
          <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Names="Calibri" 
              Font-Size="11pt" Text="Please upload images for the stud sale ..." 
              Width="320px"></asp:Label>
      </td>
  </tr>
      <tr>
          <td align="left" width="10%">
          </td>
          <td align="left" colspan="3" width="90%">
              <asp:FileUpload ID="FileUploadAll" runat="server" class="multi" />
              <br />
              <asp:Button ID="btnUploadAll" runat="server" onclick="btnUploadAll_Click" 
                  Text="Upload All" />
              <br />
              <asp:Label ID="lblStatusAll" runat="server" type="Text" /><br />
              <asp:Label ID="lblStatusAll1" runat="server" type="Text" /><br />
              <asp:Label ID="lblStatusAll2" runat="server" type="Text" /><br />
              <asp:Label ID="lblStatusAll3" runat="server" type="Text" />

And here is the code on the .aspx.vb page. Again only relevant code to the FileUpload Control:

    Protected Sub btnUploadfilePDF_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUploadfilePDF.Click

        lblStatus.Visible = True

        If Session("RefNO") = "" Then

            generateRefNo()

        End If

        If PDFFileUpload.HasFile Then

            '// Get a reference to PostedFile object
            Dim MyFile As HttpPostedFile = PDFFileUpload.PostedFile

            '// Get size of uploaded file
            Dim nFileLen As Integer
            nFileLen = MyFile.ContentLength
            Dim FileInKB As Integer
            FileInKB = nFileLen / 1024

            '// Get width of uploaded file

            'nFileWidth =




            Dim Filename As String
            Filename = System.IO.Path.GetFileName(PDFFileUpload.FileName)
            FileUpload_Name = System.IO.Path.GetFileName(PDFFileUpload.FileName)
            Session("FileUpload_Name") = FileUpload_Name
            Session("FileInKB") = FileInKB

            If FileInKB > 10000 Then
                Say("Please select a PDF file less than 10Mb")

            Else

                If ValidatePDF() Then

                    Try

                        lblStatus.Text = "You have successfully uploaded a PDF"

                        PDFFileUpload.SaveAs(Request.PhysicalApplicationPath + "/PDFs/" + Filename)

                        'Get Height and width from an image
                        'Dim fs As FileStream
                        'fs = New FileStream(MapPath("PDFs/" + Filename), FileMode.Open, FileAccess.Read, FileShare.Read)

                        'Dim image As System.Drawing.Image
                        'image = System.Drawing.Image.FromStream(fs)

                        'Dim FileWidth As Integer
                        'Dim FileHeight As Integer

                        'FileWidth = image.Width
                        'FileHeight = image.Height

                        'Session("Admin_Insert_ImageWidth") = FileWidth
                        'Session("Admin_Insert_Imageheight") = FileHeight

                        'fs.Close()
                        'fs = null

                        lblStatus.Text = "You have successfully uploaded a PDF"
                        Me.btnUploadfilePDF.Visible = False


                    Catch ex As Exception
                        lblStatus.Text = "ERROR: " + ex.Message.ToString()
                    End Try

                End If
            End If

        Else
            lblStatus.Text = "You have to select a PDF file to upload"
        End If
    End Sub



    Private Sub Say(ByVal Message As String)
        ltlAlert.Text = Message
        ' Format string properly
        Message = Message.Replace("'", "\'")
        Message = Message.Replace(Convert.ToChar(10), "\n")
        Message = Message.Replace(Convert.ToChar(13), "")
        ' Display as JavaScript alert
        ltlAlert.Text = "alert('" & Message & "')"
    End Sub

    Private Sub generateRefNo()

        'Say("Successfully Reached")
        'Dim RefNo As String
        Dim myConnection As SqlConnection = New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
        Dim myCommand As SqlCommand = New SqlCommand("ImageRefNo", myConnection)

        ' Mark the Command as a SPROC
        myCommand.CommandType = CommandType.StoredProcedure
        ' Add Parameters to SPROC

        myConnection.Open()

        Dim myReader As SqlDataReader
        myReader = myCommand.ExecuteReader

        ' Always call Read before accessing data.
        If myReader.Read Then

            Session("RefNO") = myReader.Item("UniqueID")

            'Response.Redirect("login.aspx")

        End If
        ' always call Close when done reading.
        myReader.Close()
        ' Close the connection when done with it.
        myConnection.Close()

    End Sub

    Private Function ValidatePDF() As Boolean

        'Check valid image format

        If Regex.IsMatch(Me.PDFFileUpload.FileName, "^.*[.pdf]$") Then
            Return True

        Else

            Say("Please Select Only PDF file - .pdf")
            Return False

        End If

        Return True

    End Function



    Protected Sub btnUploadAll_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUploadAll.Click

        If Session("RefNO") = "" Then

            generateRefNo()

        End If

        Try
            ' Get the HttpFileCollection
            Dim hfc As HttpFileCollection = Request.Files

            For i As Integer = 0 To hfc.Count - 1
                Dim hpf As HttpPostedFile = hfc(i)
                If hpf.ContentLength > 0 Then

                    hpf.SaveAs(Server.MapPath("images\StudStock") & "\" & System.IO.Path.GetFileName(hpf.FileName))

                    Dim myConnection As SqlConnection = New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
                    Dim myCommand As SqlCommand = New SqlCommand("Insert_Stud_Stock_Images", myConnection)
                    ' Mark the Command as a SPROC
                    myCommand.CommandType = CommandType.StoredProcedure
                    ' Add Parameters to SPROC

                    '@Order varchar(25)
                    Dim parameterOrder As SqlParameter = New SqlParameter("@Order", SqlDbType.VarChar, 100)
                    parameterOrder.Value = ""
                    myCommand.Parameters.Add(parameterOrder)

                    '@ImageName varchar(25)
                    Dim parameterImageName As SqlParameter = New SqlParameter("@ImageName", SqlDbType.VarChar, 100)
                    parameterImageName.Value = hpf.FileName
                    myCommand.Parameters.Add(parameterImageName)

                    '@ImageSize varchar(25)
                    Dim parameterImageSize As SqlParameter = New SqlParameter("@ImageSize", SqlDbType.VarChar, 100)
                    parameterImageSize.Value = hpf.ContentLength
                    myCommand.Parameters.Add(parameterImageSize)

                    '@ImageType varchar(25)
                    Dim parameterImageType As SqlParameter = New SqlParameter("@ImageType", SqlDbType.VarChar, 100)
                    parameterImageType.Value = hpf.ContentType
                    myCommand.Parameters.Add(parameterImageType)

                    '@ImageTitle varchar(25)
                    Dim parameterImageTitle As SqlParameter = New SqlParameter("@ImageTitle", SqlDbType.VarChar, 100)
                    parameterImageTitle.Value = ""
                    myCommand.Parameters.Add(parameterImageTitle)

                    '@RefNo varchar(25)
                    Dim parameterRefNo As SqlParameter = New SqlParameter("@RefNo", SqlDbType.VarChar, 25)
                    parameterRefNo.Value = Session("RefNO")
                    myCommand.Parameters.Add(parameterRefNo)


                    'Response.Write("File: " & hpf.FileName & " Size: " & hpf.ContentLength & " Type: " & hpf.ContentType & " Uploaded Successfully <br>")

                    Try
                        myConnection.Open()
                    Catch ex As Exception
                        lblStatusAll.Text = ex.ToString
                    End Try

                    Try
                        myCommand.ExecuteNonQuery()
                    Catch ex As Exception
                        lblStatusAll1.Text = ex.ToString
                    End Try

                    Try
                        myConnection.Close()
                    Catch ex As Exception
                        lblStatusAll2.Text = ex.ToString
                    End Try


                End If
            Next i
        Catch ex As Exception
            lblStatusAll3.Text = ex.ToString
       End Try
    End Sub

The only other code that is present is a form and the code to upload that forms information to a database.

On the page reload could the code that populates your listbox be running again, doubling up the number of files listed? Debug your code and see how many items are being added to the hfc collection, it may be more than you think.
Also, as an optimisation, you don't (shouldn't) use a try/catch for each step of your database interaction, particularly when all you are doing is outputting the error. Try/catch blocks are expensive to run so you should minimise their use.

you can use
return();
after inserting data for the first time in your condition ,it will avoid duplication of data,

OR

set primary key in your database it will also work,

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.