Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable object must have a value?

On the line: bool travel = fill.travel.Value; I am getting the following error:

Nullable object must have a value

and i am not sure why. All I want to do is get the value in the database of travel which is currently false. Any help would be appreciated.

using (var db = new DataClasses1DataContext()) {     var fill = (from f in db.expenseHdrs                 where f.rptNo == getPkRowReport()                 select f).FirstOrDefault();      txtReportDesc.Text = fill.description;     txtPeriod.Text = fill.period;     txtPurpose.Text = fill.purpose;      bool travel = fill.travel.Value;     chkTravel.Checked = travel   } 
like image 459
Sealer_05 Avatar asked May 11 '12 17:05

Sealer_05


People also ask

What does Nullable object must have a value mean?

According to C# Nullable Documentation If a value of type T has not been assigned to the Nullable object, you can compare it to null and retrieve its HasValue property, but you cannot access its Value property or call its other members.

What is a nullable object?

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral ("null") behavior.

What is nullable value type?

A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value. The Nullable types are instances of System.

How do you create a nullable value?

If you want to use the default value of the underlying value type in place of null , use the Nullable<T>. GetValueOrDefault() method. At run time, if the value of a nullable value type is null , the explicit cast throws an InvalidOperationException.


1 Answers

You can always switch to

 fill.travel.GetValueOrDefault() 

To provide the default (false), or the value of the boolean column from the database. Or you can specify the default with an overload. Either way, the nullable currently doesnt have a value, which is why you get that exception.

like image 121
Tejs Avatar answered Sep 20 '22 02:09

Tejs