DBNull warnings when performing stored procedure - c#

One column in my database (of type double) has some null values.
I am executing a sored procedure to get the data in my app
wipDBTableAdapters.XLSFacturiTableAdapter TAFacturi = new wipDBTableAdapters.XLSFacturiTableAdapter();
var dtfacturi = TAFacturi.GetData(CodProiect);
Then i try to do something like this:
if (dtfacturi[i].CANTITATE == null)
{
//do something
}
this is giving a warning :
The result of the expression is always 'false' since a value of type 'double' is never equal to 'null' of type 'double?
However when i run my code i get the following exception:
StrongTypingException
The value for column 'CANTITATE' in table 'XLSFacturi' is DBNull.
How am I supposed to resolve this ?

While working with data in DB and need to check NULL values use DBNull class instead of .NET null.

Database NULLs are different from null, you should use IsDBNull to check for database NULLs.
Edit: Mixed up VB.Net with C#
Compare with DBNull.Value rather than the VB specific IsDBNull.

Try this:
if (dtfacturi[i].CANTITATE == DBNull.Value)
{
//do something
}

A value of type 'double' is indeed never null; if you want to export into an array of doubles, you need to have two columns in the database, one containing the data and one containing a flag as to whether the data is valid or not.
This is really a bug in your database-to-array adapter code; I can't find any google hits for XLSFacturiTableAdapter so I'm not sure who to shout at.

DBNull is not null
Check DBNull documentation on MSDN
Try this test :
if (DBNull.Value.Equals(dtfacturi[i].CANTITATE))
{
//do something
}

When using TypedDataSets, check if coloumn is null this way..
if (dtfacturi[i].IsCANTITATENull())
{
//do something
}
Also note that, C# null is different than Database null. Type of your coloumn is double which is a value type that can never be null. In order to check if your coloumn value is null you need to compare it with DBNull.Value.

Related

Trying to save null value with arcObjects

I'm trying to save a null in an integer column with arcObjects but it always save 0 when the value is null.
Can anyone explain me what is happening?
I am developing in C#.
I tried to assign DBNull.Value to my variable but I can't because it's an integer.
Thank you very much for your time and your knowledge!
Visual Studio side:
ArcGIS side:
U need DBNull
... = (entry.Value == null) ? DBNull.Value : entry.Value;
Solved!!
Setting DBNull in this point the problem dissapear:
Shapefile does not support Null in field value and converts it to default value ie 0 for integer types. In a Geodatabase, the field "Allow NULL values" property should be set to "Yes".

DateTime accepts null value

In the web app I'm working on, the web app should be able to accept null DateTimevalues, because customers might be hesitant to give information about their Date of Birth. Of course, this won't be an easy task, because in C#, DateTime is not nullable.
DateTime rawBirthDate = Convert.ToDateTime(txtDOB.Text);
fxTxn.BirthDate = rawBirthDate;
with that, I had to change my code to accept a null value:
DateTime? rawBirthDate = string.IsNullOrEmpty(txtBirthDate) ? (DateTime?)null : DateTime.Parse(txtBirthDate);
fxTxn.BirthDate = Convert.ToDateTime(rawBirthDate);
this code, in turn, returns 1/1/0001 12:00:00.000 AM. However, MSSQL throws a DateOutOfRangeException, saying the date must be between 1/1/1753 and 12/31/9999.
I'm completely stuck in here. On my SQL table, I allowed the BirthDate column to accept null values. Question now is, how do I make C# consider null DateTime values? The end result would be that, if the Customer did not provide Date of Birth information, the system should still be able to save the record but the BirthDate column in the customer's record would still be NULL.
What you need to do is this: your column table should accept null for BirthDate (that's correct). In C#, make the variable rawBirthDate nullable.
Now, the condition you need to check is:
rawBirthDate.HasValue
If it's true, then insert the date in db.
If false, do not insert anything in the db (that's what 'allow null' means in SQL).
how do I make C# consider null DateTime values
Your value was null. The problem is that you converted it to a standard DateTime which is giving you the DateTime.MinValue (1/1/0001)
I think the problem might be in the code that actually inserts the value into database:
...
var valueToInsert = rawBirthDate ?? DBNull.Value;
...
Why are you converting null value in datetime, if you define nullable variable then it can store null vaue. Actually you need to define BirthDate property also nullable and store null value if user have not entered date like
fxTxn.BirthDate = string.IsNullOrEmpty(txtBirthDate) ? null : DateTime.Parse(txtBirthDate);
In db you need to make that column to allow null value and check value of BirthDate like
if (fxTxn.BirthDate.HasValue)
{
// pass value in db otherwise not
}

How do I get a value from a database using Oledb, I keep getting a DBNull exception?

int weaponDamage = Convert.ToInt32(dt.Rows[randomItem][2]);
// dt= DataTable
// randomItem = randomly chooses a row from the datatable
That code throws
"InvalidCastException was unhandled, Object cannot be cast from DBNull to other types".
Yes I am using the correct column and yes the entire column has values. The odd thing is sometimes the program ran, but then next time it gives the exception again. Could the problem lie with my Data Type in the database? It is set to Number and the Field Size property to Integer
Try some mitigation:
int weaponDamage = 0;
if (dt.Rows[randomItem][2] != DBNull.Value){ // I think, I'm doing this from memory.
if (int.TryParse(dt.Rows[randomItem][2].ToString(), out weaponDamage){
// Do whatever you need.
}
}
Check that the column has a value other then NULL. Then do a safe-cast of that value into an int.
There's no reason why you should randomly be getting a value one time, and then a NULL the next to be honest. That would imply that the data in the table is changing, or you are looking at different rows of data? Not sure, but I'd add some defensive coding in there to help.
What if you print the returned value first to see if it is a numeric, a string, a random object. You should also use proper try/catch blocks to avoid unhandled exceptions.

c# conversion bigint decimal

I'm working on a c# application with a sql server 2005 database.
what is the best way to convert to decimal a value brought to a datareader from a database, not knowing if the value that is coming from the base is a decimal or is a bigint ?
if (dataReader.IsDBNull(0) == false) {
PLAYER.PLAYER_ID = dataReader.GetDecimal(0);
}
In my PLAYER object, PLAYER_ID is decimal type.
I use two different databases, therefore, the value that comes from the base can be bigint or decimal. If this is decimal thete's no problem, but if it's a bigint, i get an error.
You should be able to use the GetFieldType method to determine the data type of the object.
You can use GetFieldType to determine the type
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getfieldtype.aspx
Type type = dataReader.GetFieldType(0);
You can then use an appropriate reader method to read out the data.
You probably want to avoid calling GetFieldType for every row. Call it before you start reading rows and set a flag indicating which type this particular query returned.
Use Decimal.TryParse:
decimal tempID;
Decimal.TryParse(dataReader[0], out tempID);
PLAYER.PLAYER_ID = tempID;
It should convert the value to the decimal unless it's null. If it's null decimal will remain 0.

Dataset allowing Null values even when AllowDBNull = False?

I have designed a dataset using VS2008 dataset designer. In one of the datatables, I have set "AllowDBNull" property of most of the columns to be False. However, still if I create a DataRow containing null values for these columns, this datatable accepts this row, without any error.
Am I not understanding something here? Please advice. Thank you.
Edit Mike Spross' excellent explanation however, brings forth another question. How do we check text fields if they are System.DBNull? It is surprising that DataSets are not considering a string "" as System.DBNull and throwing an exception. Or is it not?
Edit I think I have found the problem and reason. I am initializing a new row of the DataTable, before filling in the values to that row. While initializing the row, default value for string, ie, "" might be being filled in that column. I think that's it? Any ideas about this?
The short answer is:
System.DBNull.Value != null
The longer answer is:
In C#, the concept of a NULL value in SQL is represented by the Value property of the System.DBNull class. When dealing with a database, the more familiar C# null doesn't actually mean "null value."
When you set a database column to null, ADO.NET will initialize the column to whatever the default value is for that column (for example, an int column would be initialized to 0). That is, using null can actually cause a non-null value to end up in the database, and therefore you won't get an error.
If you instead set a database column to System.DBNull.Value, the column will actually be set to NULL. This is the situation that AllowDBNulls == false will prevent you from doing.
Regarding your "bonus" ;-) question: NULL (no string) and "" (empty string) are two different things. So it's perfectly reasonable to treat them differently. It's the distinction between null and DBNull that is messing things up. If nullable types had been available at the time of designing ADO.NET, things probably would be a lot easier. But before .NET 2.0, there was no way to represent e.g. a "null integer".
Are you exactly assigning NULL values or an empty string to those columns? If you don't assign any value to a column, it will default to NULL (if a DEFAULT constraint is not imposed). Else you can assign a NULL value by doing -
ds.Tables[0].Rows[0]["Col"] = null;
If you are assigning an Empty string to those columns, it's not equal to NULL.
And if you have a NULL value in a column which has been marked as NOT NULLABLE, it will throw an error -
Column 'Col1' does not allow nulls.
EDIT:
By NOT NULLABLE, I mean AllowDBNull = false.
Your code seems correct. Can you try trimming the text?
Here's the whole code -
DataTable dt = new DataTable();
DataColumn column = new DataColumn("Col1");
column.AllowDBNull = false;
dt.Columns.Add(column);
DataRow dr = dt.NewRow();
dr["Col1"] = null;
dt.Rows.Add(dr);

Categories

Resources