Trying to save null value with arcObjects - c#

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".

Related

Why date filed is not taking null but 1900-01-01? [duplicate]

This question already has answers here:
datetime issue with 01/01/1900
(3 answers)
Closed 6 years ago.
I have been working on a backend i.e. in Sql server 2012. I have declare a field as Date in table i.e. ParawiseDate datetime.
And I am passing a NULL to it from C# i.e.
sqlcom.Parameters.AddWithValue("#ParawiseDate", NULL);
Problem:
It saves the dates as 1900-01-01 instead of NULL. I tried "" and also got saved as 1900-01-01.
Why ?
Make sure it allow null values in ParawiseDate column.Also instead of passing Null try DBNull.value
sqlcom.Parameters.AddWithValue("#ParawiseDate", DbNull.Value);
SELECT cast(NULLIF(t.[ParawiseDate],'') AS DATE)
FROM tablename t
I believe for DateTime, you can declare the type with "?" , otherwise they would default to 1900-01-01
DateTime ? Parameter;
Also try passing in
typeof(System.DateTime)
instead of NULL, on the second parameter
It is essential to know what binary representation of data is and what casts are allowed. Without that, any programmer is somewhat blind. Regarding this case, in MS SQL default date value is 1900-01-01. In older CLR AddWithValue with DBNull.Value as a value was equivalent to setting field to default.
I didn't dealt with 4.0 CLR environment, but I may expect that NULL could be casted to DBNull? In any case it is not a date value, or if NULL could be implicitly casted into Date with a default value? (latter would say that MS again steps away from standards, NULL must now be equal to pointer to any object) Most likely an undocumented side-effect.
public SqlParameter AddWithValue(
string parameterName,
object value
)
Parameters
parameterName
Type: System.String
The name of the parameter.
value
Type: System.Object
The value to be added. Use DBNull.Value instead of null, to indicate a null value.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx
Date and DateTime cannot be NULL, though field in table can be set to allow null values. Reading no data usually would get result in getting default value, for safety reasons. That requires separate check (isDBNull?)
Only legitimate values for date in SQL (Microsoft flavor at least) are 0001-01-01 through 9999-12-31 , that should be given explicitly, otherwise a default would be used.

How to handle Null value in Data Link Layer?

I'm working in Asp.net WCF. I'm displaying a table in front end, with the data taken from back end. One of the column having datatype date, contains Null value in backend. When i try to run the solution it displays error page because of the Null value, for the column. How can i avoid this error ?
I think you're looking for SqlDataReader.IsDBNull Method
Check whether the database field contains null value
Handle it with String.Empty
Here is an sample that I have used
logSource = (!reader.IsDBNull(0)) ? reader.GetString(0).Trim() : "";
From your comments,
ObjUnutilizedOwnershipEntities.Dt_VisaValidFrom = (!IsDBNull(osqlDataReader["Dt_VisaValidFrom"]))
? Convert.ToDatetime(osqlDataReader["Dt_VisaValidFrom"].ToString())
: "";

Autogenerate columns null values

I want to save null values to a decimal column(allows nulls on db) on a wpf datagrid (with autogenerate columns).
It doesn't allow me to save nulls and shows red error box.
I suspect you are running into a problem that I had but it was a simple text box (not a datagrid). You think you are passing a null but you are really passing string.empty which is neither null nor a decimal. I fixed it with a converter to convert string.empty to null. H.B. (the same H.B.) that edited your question answered mine.
Cannot Assign a Null Value to a Nullable Int32? via Binding
to which kind of database are you binding your datagrid to ? for instance if you bind it to a datatable with ado.net, the datatable is not aware of the underlying sql schema unless you update it yourself. --> see http://support.microsoft.com/kb/310128
with linq2sql it should work fine without this update, with others like MySql i don't know.
Just add this code in AutogeneratingColumn event:
if (e.Column.ToString() ==
"System.Windows.Controls.DataGridTextColumn")
{
(((System.Windows.Controls.DataGridBoundColumn)(e.Column)).Binding).TargetNullValue
= string.Empty;
}

DBNull warnings when performing stored procedure

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.

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