无法将类型为'system.dbnull'的对象强制转换为'system.byte [] [英] Unable to cast object of type 'system.dbnull' to type 'system.byte[]

查看:224
本文介绍了无法将类型为'system.dbnull'的对象强制转换为'system.byte []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是年轻的vb程序员,我想从sql数据库中检索数据,它的工作正常但是当我尝试检索没有图片保存的数据时它给了我这个错误:无法转换类型为'System.DBNull'的对象输入'System.Byte []





这些是我的代码:



I am young vb programmer, i want to retrieve data from sql database, its works fine but when i try to retrieve data that was saved without picture it gives me this error: Unable to cast object of type 'System.DBNull' to type 'System.Byte[]


These are my code:

Dim cmd As New SqlCommand("SELECT EmpID,Fname,Oname,Lname,Date_hired,Branch,Department,Grade,Pictures FROM Staff_Information WHERE EmpID = '" & txtempID.Text & "'", con)
      con.Open()
      Dim sdr As SqlDataReader = cmd.ExecuteReader()

      If sdr.HasRows Then
          While sdr.Read()

              txtfname.Text = sdr.Item("Fname").ToString
              txtothername.Text = sdr.Item("Oname").ToString
              txtlname.Text = sdr.Item("Lname").ToString
              dtpempl.Value = sdr.Item("Date_hired").ToString
              txtbranch.Text = sdr.Item("Branch").ToString
              txtdepartment.Text = sdr.Item("Department").ToString
              txtgrade.Text = sdr.Item("Grade").ToString

              Dim data As Byte() = DirectCast(sdr("Pictures"), Byte())
              Dim ms As New MemoryStream(data)
              PictureBox.Image = Image.FromStream(ms)

          End While
          sdr.Close()
          btnsearch.Enabled = False
          txtempID.ReadOnly = True
          btnclear.Enabled = True
      Else
          MsgBox("Staff ID: " & txtempID.Text & " " & "not found.")
          txtempID.Clear()
          txtempID.ReadOnly = False
          btnsearch.Enabled = False
          btnclear.Enabled = False
      End If
      con.Close()





什么我试过了:



试过这段代码:





What I have tried:

tried this code:

If sdr("Pictures") IsNot System.DBNull Then
                   Dim data As Byte() = DirectCast(sdr("Pictures"), Byte())
                   Dim ms As New MemoryStream(data)
                   PictureBox.Image = Image.FromStream(ms)
               End If





但是,System.DBNull是下划线红色并给出此消息:DBNull是class和ca. n不能用作表达式



but,System.DBNull is Underline red and gives this message:DBNull is class and can not be used as an expression

推荐答案

因此,您需要先检查数据库返回的值是否为System.DBNull。如果它不是System.DBNull,那么你可以正常处理你的图像。



You therefore need to check if the value returned from your DB is System.DBNull first. If it is not System.DBNull then you can process your images as normal.

If sdr("Pictures") IsNot System.DBNull
  Dim data As Byte() = DirectCast(sdr("Pictures"), Byte())
  Dim ms As New MemoryStream(data)
  PictureBox.Image = Image.FromStream(ms)
End If


尝试System.DBNull.Value。正如错误所说,Syste.DBNull是一个类,Value是一个布尔属性。



Try System.DBNull.Value . As the error says, Syste.DBNull is a class and Value is a boolean property in it.

If sdr("Pictures") IsNot System.DBNull.Value
  Dim data As Byte() = DirectCast(sdr("Pictures"), Byte())
  Dim ms As New MemoryStream(data)
  PictureBox.Image = Image.FromStream(ms)
End If


首先修复 SQL注射 [ ^ ]漏洞。



您还需要在中使用块,以确保它们始终被正确清理。



由于您只显示单个记录的结果,因此您不能需要一个循环来读取记录。

Start by fixing the SQL Injection[^] vulnerability in your code.

You'll also want to wrap the connection, command, and data reader objects in Using blocks, to ensure that they're always cleaned up properly.

Since you're only displaying the results for a single record, you don't need a loop to read the record.
Using con As New SqlConnection("...")
    Using cmd As New SqlCommand("SELECT EmpID, Fname, Oname, Lname, Date_hired, Branch, Department, Grade, Pictures FROM Staff_Information WHERE EmpID = @EmpID", con)
        
        cmd.Parameters.AddWithValue("@EmpID", txtempID.Text)
        
        con.Open()
        Using sdr As SqlDataReader = cmd.ExecuteReader()
            If sdr.Read() Then
                txtempID.ReadOnly = True
                txtfname.Text = Convert.ToString(sdr.Item("Fname"))
                txtothername.Text = Convert.ToString(sdr.Item("Oname"))
                txtlname.Text = Convert.ToString(sdr.Item("Lname"))
                dtpempl.Value = Convert.ToDateTime(sdr.Item("Date_hired"))
                txtbranch.Text = Convert.ToString(sdr.Item("Branch"))
                txtdepartment.Text = Convert.ToString(sdr.Item("Department"))
                txtgrade.Text = Convert.ToString(sdr.Item("Grade"))
                
                Dim pictureIndex As Integer = sdr.GetOrdinal("Pictures")
                If sdr.IsDBNull(pictureIndex) Then
                    PictureBox.Image = Nothing
                Else
                    Dim data As Byte() = DirectCast(sdr(pictureIndex), Byte())
                    Dim ms As New MemoryStream(data)
                    PictureBox.Image = Image.FromStream(ms)
                End If
            Else
                MsgBox("Staff ID: " & txtempID.Text & " " & "not found.")
                txtempID.Clear()
                txtempID.ReadOnly = False
            End If
        End Using
    End Using
End Using

btnsearch.Enabled = False
btnclear.Enabled = True




你想知道关于SQL注入的一切(但不敢问)特洛伊亨特 [ ^ ]

如何在没有技术术语的情况下解释SQL注入? |信息安全堆栈交换 [ ^ ]

查询参数化备忘单| OWASP [ ^ ]



Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]


这篇关于无法将类型为'system.dbnull'的对象强制转换为'system.byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆