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