1

I'm just start to make an application. I got some textfield that must filled with integer value, but when the textfield is empty, I want the value is still null in database rather than must add "0".

it's something like this

        DR.IN = Me.txtIn.Text
        DR.OUT = Me.txtOut.Text

the two of that is integer value, that when i'm save to data base the error comes and said

The Nullable Object Must Have Value

I must add "0", but I want the data is still null. Do anyone know how to do that?

thanks for your help and sorry for really bad grammar, I hope someone out there would understand my question :)

6
  • 2
    What is DR.IN and DR.OUT? Where is the error raised? Commented Sep 23, 2015 at 7:42
  • Me.txtIn.Text != nothing then Me.txtIn.Text else nothing.But make sure DR.IN and DR.OUT are nullable ints.Something like Dim DR.IN? as int Commented Sep 23, 2015 at 7:46
  • @TimSchmelter it's class that I made Commented Sep 23, 2015 at 7:53
  • @AmitKumarGhosh uumm.. I'm not sure I understand that, sorry Commented Sep 23, 2015 at 7:54
  • @Matt has come up with what I meant. Commented Sep 23, 2015 at 7:57

4 Answers 4

3

You can just do a conditional check using the If Operator to return either Nothing (null) if there is no text in the textbox or the integer value of the textbox:

Dim value As Integer? = If(TextBox1.Text.Length = 0, Nothing, Integer.Parse(TextBox1.Text))
Sign up to request clarification or add additional context in comments.

1 Comment

hey, yeah! this is all I need. Thank's so much!
0

You haven't shown some rather important information but I'm going to assume that you are using the Value property of your Integer? without first checking whether it actually has a value. That's the whole point of a Nullable: it can have a value or not. You can't use the value if there isn't one. Saving an Integer? might look like this:

Dim command as new SqlCommand

command.CommandText = "UPDATE MyTable SET Number = @Number WHERE ID = @ID"

command.Parameters.Add("@Number", SqlDbType.Int).Value = If(myNullableInteger.HasValue,
                                                            myNullableInteger.Value,
                                                            CObj(DBNull.Value))

Comments

0

You can make a nullable integer in C# like :

int? myint;

and in VB.net like:

Dim myint As Integer? 

Comments

-1

Using default(Nullable<type>) will return you a Nullable<type> set to null.

2 Comments

My bad... Question was flagged C# initially. I'm no VB.Net expert :$
that's okay, also my bad to add C# tag, that I don't even remember I've add that tag xD

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.