2

I want to bring records stored in my SQL server DB to my form in VB.NET, I did below coding and it works fine but is there any other better way to handle NULL value from DB column that is going to be displayed in the textbox?

If DBNull.Value.Equals(dt.Rows(0).Item("fine_amt")) Then
                txtFine_amt.Text = ""
            Else
                txtFine_amt.Text = dt.Rows(0).Item("fine_amt")
            End If

If we don't handle Null value then it is going to throw an error: Conversion from type 'DBNull' to type 'String' is not valid

3
  • 1
    "Better" in what way? extract the value to a variable? Use a conditional operator? Commented Jan 8, 2016 at 14:03
  • 1
    See also this Commented Jan 8, 2016 at 14:31
  • @Plutonix thanks just checked it Commented Jan 8, 2016 at 15:56

2 Answers 2

3

If I'm reading your question right, it sounds like you could just do this:

txtFine_amt.Text = dt.Rows(0).Item("fine_amt").ToString()

For null values, ToString() will always just return an empty string.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you this seems better and short way to achieve same thing :)
2

Not sure if it's really "better" but you could extract the value to a variable and use a conditional operator:

Dim value As Object = dt.Rows(0).Item("fine_amt")
txtFine_amt.Text = If(DBNull.Value.Equals(value), "", value)

3 Comments

Thank you! looks fine. I was curious that how many ways are available to handle Null value coming from DB into VB form
@Hazmat Well, you're handling the null value the exact same way - it just reorganizes the code a little to make it more compact. Use whatever methods you can to get it to work, then focus on making it better. Shorter code is not always better code.
Thank you Stanley for the advice

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.