Conversion from type 'DBNull' to type 'String' is not valid

后端 未结 8 659
攒了一身酷
攒了一身酷 2020-12-09 16:06

i am receiving this problem

Conversion from type \'DBNull\' to type \'String\' is not valid.

Line 501: hfSupEmail.

相关标签:
8条回答
  • 2020-12-09 16:39

    The quick and dirty fix:

    hfSupEmail.Value = dt.Rows(0)("SupEmail").ToString()
    

    or for C#:

    hfsupEmail.Value = dt.Rows[0]["SupEmail"].ToString();
    

    This works very well when your eventual target and the source data are already strings. This is because any extra .ToString() call for something that's already a string will generally be optimized by the jitter into a no-op, and if it's NULL the resulting DBNull.Value.ToString() expression produces the empty string you want.

    However, if you're working with non-string types, you may end up doing significant extra work, especially with something like a DateTime or numeric value where you want specific formatting. Remember, internationalization concerns mean parsing and composing date and number values are actually surprisingly expensive operations; doing "extra" work to avoid those operations is often more than worth it.

    0 讨论(0)
  • 2020-12-09 16:43

    Hope This Help.... dt.Rows(0)("SupEmail") returns null

    To avoid this chcek before assigning

    If Not IsDBNull(dt.Rows(0)("SupEmail")) Then
        hfSupEmail.Value = dt.Rows(0)("SupEmail")
    End If
    
    0 讨论(0)
  • 2020-12-09 16:43

    You can use the Field method of the Datarow combined with an If Operator to check for a Null value in one line like this. If it is null, you can replace it with an empty string (or another string of your choosing):

    hfSupEmail.Value = If(dt.Rows(0).Field(Of String)("SupEmail"), "")
    
    0 讨论(0)
  • 2020-12-09 16:48

    Apparently your dt.Rows(0)("SupEmail") is coming as NULL from DB and you cannot assign NULL to string property. Try replacing that line with:

    hfSupEmail.Value = If(IsDbNull(dt.Rows(0)("SupEmail")), String.Empty, dt.Rows(0)("SupEmail").ToString)
    

    The code checks if value is NULL and if it is - replaces it with empty string, otherwise uses original value.

    0 讨论(0)
  • 2020-12-09 16:49

    The easiest way is probably to just concatenate it with an empty string:

    hfSupEmail.Value = dt.Rows(0)("SupEmail") & ""
    
    0 讨论(0)
  • 2020-12-09 16:49
            con.Open()
            cmd = New SqlCommand
            cmd.CommandText = " select  sum (Income_Amount)  from Income where Income_Month= '" & ComboBox1.Text & "' and Income_year=" & txtyearpro.Text & ""
            cmd.Connection = con
            dr = cmd.ExecuteReader
            If dr.Read = True Then
                txtincome1.Text = dr(0).ToString  ' ToString  converts null values into string '
    
            End If
    
    0 讨论(0)
提交回复
热议问题