0

while using the given below code showing one error. The error is : Operator '<>' is not defined for type 'DBNull' and string "". Help me to find a proper solution. Thank You.

Code:

 If sdr1.Read Then
   If sdr1(1) <> "" Then
     NameLabel.Text = sdr1(0).ToString + " " + sdr1(1).ToString + " " + sdr1(2).ToString
   Else
     NameLabel.Text = sdr1(0).ToString + " " + sdr1(2).ToString
   End If
     dept_id.Text = sdr1(3)
 End If
   sdr1.Close()
1
  • In VB & is the string concatenation operator, not +. Commented Apr 2, 2015 at 5:08

5 Answers 5

3

You need to check whether the data you are comparing is NULL or not before you use it inside any operation:

If sdr1.Read Then
   If Not IsDbNull(sdr1(1)) Then
     If sdr1(1) <> "" Then
       NameLabel.Text = sdr1(0).ToString + " " + sdr1(1).ToString + " " + sdr1(2).ToString
     Else
       NameLabel.Text = sdr1(0).ToString + " " + sdr1(2).ToString
     End If
    End If
    dept_id.Text = sdr1(3)
End If
   sdr1.Close()

or you can simply use

If sdr1.Read Then
   If Not IsDbNull(sdr1(1)) Then
       NameLabel.Text = sdr1(0).ToString + " " + sdr1(1).ToString + " " + sdr1(2).ToString
   Else
       NameLabel.Text = sdr1(0).ToString + " " + sdr1(2).ToString
   End If
   dept_id.Text = sdr1(3)
End If
sdr1.Close()
Sign up to request clarification or add additional context in comments.

Comments

2

Your column contains a null value. You have to check for nullness before trying to do other comparisons.

So...

If DBNull.Value Is sdr1(1) Then
    '  Got a null value from the database.
End If

If you don't care about whether the value is null, or empty - just want to treat them the same...

If String.IsNullOrEmpty(sdr1(1)) Then
    '  The value is either null or empty.
End If

Comments

1

Use If sdr1(1) IsNot "" Then or If Not IsDBNull(sdr1(1)) Then instead for <> that will give you better result

Comments

0

Use String.IsNullorEmpty instead for checking the same

Ex:-

If Not String.IsNullOrEmpty(x) Then
  'Do Something
End If

Comments

0

Use instead of If function

try
If sdr1.Read Then
   If Not IsDbNull(sdr1(1)) Then
       NameLabel.Text = sdr1(0).ToString + " " + sdr1(1).ToString + " " + sdr1(2).ToString
   Else
       NameLabel.Text = sdr1(0).ToString + " " + sdr1(2).ToString
   End If
   dept_id.Text = sdr1(3)
End If
Catch ex As Exception

end try

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.