locked
image upload cannot accept null value RRS feed

  • Question

  • User-655038425 posted

    please somebody review my code for me, i wish sometimes it accept null value

        Protected Sub imgupload2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles imgupload2.Click
            Dim connection As SqlConnection = Nothing
    
            Try
                Dim img As FileUpload = CType(imgupload, FileUpload)
                Dim imgbyte As Byte() = Nothing
    
                If img.HasFile AndAlso Not img.PostedFile Is Nothing Then
    
                    Dim file As HttpPostedFile = imgupload.PostedFile
    
                    imgbyte = New Byte(file.ContentLength - 1) {}
                    file.InputStream.Read(imgbyte, 0, file.ContentLength)
    
                End If
    
                Dim conn As String = ConfigurationManager.ConnectionStrings("albumConnString").ConnectionString
                connection = New SqlConnection(conn)
    
    
                connection.Open()
                Dim sql As String = "insert into test(name, age, photo) values (@aname, @aage, @aphoto) SELECT @@IDENTITY"
    
                Dim cmd As SqlCommand = New SqlCommand(sql, connection)
                cmd.Parameters.AddWithValue("@aname", name.Text.Trim())
                cmd.Parameters.AddWithValue("@aage", age.Text)
                cmd.Parameters.AddWithValue("@aphoto", imgbyte)
                Dim id As Integer = Convert.ToInt32(cmd.ExecuteScalar())
                lblresult.Text = String.Format("picture id is {0}", id)
    
            Catch
                lblresult.Text = "There was an error"
    
    
            Finally
                connection.Close()
            End Try
    
            name.Text = ""
            age.Text = ""
    
         
    
        End Sub
    Saturday, March 10, 2012 12:45 AM

Answers

  • User-821857111 posted

    Dont' you want to move that End If from the point just before you create and open a connection to a point after the End Try? That way. no database operation will be attempted unless the img.HasFile AndAlso Not img.PostedFile Is Nothing condition is met.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, March 10, 2012 3:56 AM