-1

I am getting an error on this line within my code:

[bytes = DirectCast(sdr("MedicalCertificateID"), Byte())]

Do you know what is wrong?

  Protected Sub btnDownload_Click(sender As Object, e As EventArgs)

        Dim MedicalCertificateID As Integer = Integer.Parse(TryCast(sender, LinkButton).CommandArgument)
        Dim bytes As Byte()
        Dim fileName As String, contentType As String

        Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("##").ConnectionString)

            Using cmd As New SqlCommand("SELECT * FROM tblMedicalResults WHERE MedicalCertificateID  = @MedicalCertificateID", conn)

                cmd.Parameters.AddWithValue("@MedicalCertificateID", MedicalCertificateID)

                conn.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    sdr.Read()
                    bytes = DirectCast(sdr("MedicalCertificateID"), Byte())
Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
Tevin
  • 21
  • 6
  • Why are you trying to read a value that you already know? _MedicalCertificateID_ is used in the WHERE statement to find a record that matches that variable's value. – Steve Jun 24 '19 at 07:44
  • @Steve - Then what will be the best way to handle this ? – Tevin Jun 24 '19 at 07:49
  • Please stop using `.AddWithValue` See http://www.dbdelta.com/addwithvalue-is-evil/ and https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ and another one: https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications – Mary Jun 24 '19 at 15:26
  • You say the "name of the file" is stored in the database. The name of a file would be a string. Is the file itself stored in the database? It would not be stored in an Integer datatype. You are changing an Integer to a Byte array. This would have nothing to do with a file or file name. – Mary Jun 24 '19 at 15:32

1 Answers1

0

If you just need to convert an integer value to its byte representation you need only one line of code

 Dim bytes As Byte() = BitConverter.GetBytes(MedicalCertificateID)

There is no need to run a query against the database because the variable MedicalCertificateID is used in the WHERE statement to find a record with the a field containing the value that you want to read back.
If you want to check the record existance then you should simply check the return value of sdr.Read with

Using sdr As SqlDataReader = cmd.ExecuteReader()
    if sdr.Read() Then 
       ' record exists....
    End If 
End using
Steve
  • 213,761
  • 22
  • 232
  • 286