I am trying to read nullable values from a database. Right now my code is converting null values to false. How can I modify my code to allow for null values?
Ap1ExamTaken = dr["AP1_ExamTaken"] != DBNull.Value && Convert.ToBoolean(dr["AP1_ExamTaken"]),
I would like values that are null to be shown as null and not false.
You could use the conditional operator here, to set it to null if the value is DBNull.Value, or a non-nullable value otherwise:
Ap1ExamTaken = dr["AP1_ExamTaken"] == DBNull.Value ? null : (bool?) dr["AP1_ExamTaken"];
Note that this will throw an exception if dr["AP1_ExamTaken"] is a non-boolean, non-DBNull type, which I suspect is what you want.
You could write it more compactly as:
Ap1ExamTaken = dr["AP1_ExamTaken"] as bool?
... but then you'll end up with a null value if the value is some other type (a string, an integer etc) which I'd generally be alarmed about. (If my data doesn't have the shape I expect, I want to know ASAP.)
Related
I'm trying to read in items from a spread sheet into a data table, which can then be uploaded to a database.
The column I'm having issues with has to read in values that are boolean values. However, sometimes the field is empty. Instead of 0's and 1's, I need to store null into this boolean value when the field is empty.
Here is the original line of code:
bool bool2 = Convert.ToBoolean(row["Bool_02"]);
This works well when the field isn't empty.
But I can't check if the field is empty first because you can't store null as a boolean value.
I tried making it a nullable value like so:
bool? bool2 = Convert.ToBoolean(row["Bool_02"]);
if(bool2 != true || false)
{
bool2 = null;
}
But I get an error - object cannot be cast from DBNull to other types.
I have to take the input of the column, check if its empty - if its empty then save null in the bool variable.
How can I do this?
But I can't check if the field is empty first because you can't store null as a boolean value.
Sure you can, just check if the field is DBNull before trying to convert it.
if(row["Bool_02"] is DBNull) return;
bool bool2 = Convert.ToBoolean(row["Bool_02"]);
If you'd like to stuff it in a nullable boolean, you need a ternary.
bool? bool2 = row["Bool_02"] is DBNull ? null : Convert.ToBoolean(row["Bool_02"]);
Untested, you might need a typecast to (bool?) in that ternary for it to compile.
I want to check the following field in the datatable against null :
r.Field<int>("prod_type")
if (r.Field<int>("prod_type") != null &&
!string.IsNullOrEmpty(r.Field<int>("prod_type").ToString()))
but I get the following exception :
Specified cast is not valid.
How to check the integer value in the datatable against null or empty ?
The Field extension method supports nullable types. Use HasValue to check if a nullable is not null:
if (r.Field<int?>("prod_type").HasValue)
The error you are getting is indicating that the field in the datatable is not of type int. If it is of type int it can't hold null value, instead you can try int? which is Nullable.
r.Field<int?>("prod_type") != null
If prod_type is indeed an int field in the database, try doing it like this:
if (r.Field<int?>("prod_type") != null)
I've got an object, specifically the following:
table.ExtendedProperties["MS_Description"].Value
If there is not property, the Value is null. If there is a property, but it is empty, the Value.toString() is "".
I would thus like to create an if-statement which caters for both eventualities. This is what I've done so far:
if (table.ExtendedProperties["MS_Description"] == null ||
table.ExtendedProperties["MS_Description"].Value.ToString().Equals(""))
The problem is that if it is null, it is still checking the condition on the right-hand-side.
Any ideas?
You can do:
if (table.ExtendedProperties["MS_Description"] == null || string.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value))
The reason your code errors is because you don't check if table.ExtendedProperties["MS_Description"].Value is null.
Thus Value is not a string, then you have to deal with all conditions:
var description = table.ExtendedProperties["MS_Description"];
if (description == null ||
description.Value == null ||
description.Value.ToString().Equals(""))
// no value
BTW your code is not quite correct
if (table.ExtendedProperties["MS_Description"] == null ||
table.ExtendedProperties["MS_Description"].Value.ToString().Equals(""))
Instead of checking Value for null, you are checking if table.ExtendedProperties["MS_Description"] is not null. Thats true. You go further, but if table.ExtendedProperties["MS_Description"].Value is null (you didn't check that, remember?), you will get NullReferenceException on applying ToString().
I'm not sure if you are referring to the DataTable.ExtendedProperties property or something else, but if you are, the property returns a System.Data.PropertyCollection, which inherits from System.Collections.HashTable.
Most of the methods and properties, including the indexer ("Item") being discussed here, are directly inherited from HashTable, so in general, table.ExtendedProperties[key] can return any object, including null.
Note that you can also call DataTable.ExtendedProperties.ContainsKey(object key) to determine if the PropertyCollection contains a specific key or not.
Do you know what type of object you are retrieving when you call table.ExtendedProperties["MS_Description"].Value ?
If so, there might be other properties you can use to determine whether the property has been set, etc.
Depending on what type of object table.ExtendedProperties["MS_Description"] is, you might even be able to do something like this:
if ((table.ExtendedProperties["MS_Description"] ?? "").ToString().Length == 0) {
.....
}
That would take into account all of the possibilities:
the key doesn't exist
the key exists, but the value is null
the key exists and the value is empty
as long as the table.ExtendedProperties["MS_Decription"] object returns "" when its Value property is either null or empty.
So a little more information on the object that is returned could go a long way!
string.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value)
It looks like table.ExtendedProperties["MS_Description"] is never null, you should be null checking the Value property instead
string value = table.ExtendedProperties["MS_Description"].Value;
if (value == null || value.ToString().Equals(""))
// OR
if (String.IsNullOrEmpty(value))
If table.ExtendedProperties["MS_Description"] can return null, then you need
if (table.ExtendedProperties["MS_Description"] == null ||
String.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value.ToString() )
And since table.ExtendedProperties["MS_Description"].Value may return null, then you need
if (table.ExtendedProperties["MS_Description"] == null ||
table.ExtendedProperties["MS_Description"].Value == null ||
String.IsNullOrEmpty(table.ExtendedProperties["MS_Description"].Value.ToString() )
I had ddl which determine gender and user can donot choose any value from ddl so i tried to check if user didnot select any value from ddl inser null value or any value in database i made that but error apear(Procedure or Function 'InsertRegisteration' expects parameter '#Gender_Id', which was not supplied).any one help me
(My Code)
if (DDLGender.SelectedItem.Value[0]!= null )
{
command.Parameters.Add("#Gender_Id",SqlDbType.Int).Value=null;
}
else
{
command.Parameters.Add(Parameter.NewInt("#Gender_Id", DDLGender.SelectedValue));
}
Try this:
if (DDLGender.SelectedItem.Value[0]!= null )
{
command.Parameters.Add("#Gender_Id",SqlDbType.Int).Value= DBNull.Value;
}
else
{
command.Parameters.Add(Parameter.NewInt("#Gender_Id", DDLGender.SelectedValue));
}
Added : Difference between null and System.DbNull.Value
Well, null is not an instance of any type. Rather, it is an invalid reference.
However, System.DbNull.Value, is a valid reference to an instance of System.DbNull (System.DbNull is a singleton and System.DbNull.Value gives you a reference to the single instance of that class) that represents nonexistent* values in the database.
*We would normally say null, but I don't want to confound the issue.
So, there's a big conceptual difference between the two. The keyword null represents an invalid reference. The class System.DbNull represents a nonexistent value in a database field. In general, we should try avoid using the same thing (in this case null) to represent two very different concepts (in this case an invalid reference versus a nonexistent value in a database field).
Keep in mind, this is why a lot of people advocate using the null object pattern in general, which is exactly what System.DbNull is an example of.
Try this:
if (DDLGender.SelectedIndex == 0 )
{
command.Parameters.Add("#Gender_Id", DBNull.Value);
}
else
{
command.Parameters.Add("#Gender_Id", (int)DDLGender.SelectedValue);
}
You don't have to specify the data type for parameters.
Assuming you are using stored procedure for updating,
I think you can make the change in stored procedure to have default value to this INT column as NULL which will make this parameter optional. Then you can execute only the ELSE part here from code.
You can combine the above lines of code to :
cmd.Parameters.Add(new SqlParameter { SqlDbType = SqlDbType.Int, Value = DDLGender.SelectedIndex!=0 ? (int)DDLGender.SelectedValue : null });
The use of Null coalescing operator will do the null check. If the selectedItem is not null then that will be passed in as value otherwise null will be passed.
I have an Oracle data table fetching columns that be null. So I figure to keep the code nice and simple that I'd use the ?? operand. AlternatePhoneNumber is a string in my C# model.
AlternatePhoneNumber = customer.AlternatePhoneNumber ?? ""
However, even with that code I still get the error.
System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.
I know what the error means but why is ?? not usable on DBNull? Isn't null and DBNull essentially the same?
Thank you.
The ?? operator only applies to actual nulls.
null and DBNull.Value are not the same; DBNull.Value is simply a placeholder object.
Also, that exception is coming from inside the AlternatePhoneNumber property, before your ?? operator executes. (Your code doesn't have a cast).
If customer is a row in a typed dataset, change the column's NullValue property in the designer.
null and DBNull are not the same. System.DBNull is an actual object.
The problem is that AlternatePhoneNumber is a string. DBNull is not.
Try this instead:
AlternatePhoneNumber = (customer.AlternatePhoneNumber as string) ?? ""
Do this:
public T IfNull<T>(object o, T value)
{
return (o == DbNull.Value) ? value : (T)o;
}
DBNull is a type with a single value, and is not the same as a null string reference, which is why you can't use ??. You could do this however:
string alternativePhoneNumber = DBNull.Value.Equals(customer) ? string.Empty : ((Customer)customer).AlternatePhoneNumber;
As other replies state, null means a reference that refers to no object, while DBNull is a class supplied by ADO.NET to indicate when a field or value is NULL at the database (or in a DataTable).
While you can use the conditional (ternary) operator (?:) to do what you want:
AlternatePhoneNumber = customer.AlternatePhoneNumber is DBNull
? ""
: customer.AlternatePhoneNumber;
I tend to wrap this up in an extension method:
static class NullExtensions
{
public static T WhenNull<T>( this object value, T whenNullValue )
{
return (value == null || value is DBNull)
? whenNullValue
: (T)value;
}
}
which I find makes the code easier to read and understand.
AlternatePhoneNumber = customer.AlternatePhoneNumber.WhenNull( "" );
DBNull is NOT a real "null".
The "??" - operator detects only null - references, not objects that emulate "null" behavior.