I have a column with SQL type of smallint (EF type of Int16) that I want to insert a null value into but when I use the below code I get the error that null can not be converted to short. How can I get this one line if statment to allow me to insert a null?
CollectionID = (ddlCollection.SelectedValue == "None") ? null : Convert.ToInt16(ddlCollection.SelectedValue)
Working code is to do a nullablecnvert like:
CollectionID = (ddlCollection.SelectedValue == "None") ? (Nullable<Int16>)null : Convert.ToInt16(ddlCollection.SelectedValue)
c# has a values for null in database:
DBNull.Value
The first problem is that your Entity Framework property CollectionID must be marked as Nullable (if you're using EDMX) or declared as short? or Nullable<short> if you're using Code First.
Secondly, you need to make sure the database type for that column is also marked as nullable (something like smallint NULL in SQL Server).
EDIT: Ah, I think I see the problem now. Try casting your call to Convert.ToInt16 to Nullable<short>. The ternary operator sees a null on the true side, and type incompatible with the null value on the false side, which is causing your error.
CollectionID = (ddlCollection.SelectedValue == "None")
? (Nullable<short>)null
: (Nullable<short>)Convert.ToInt16(ddlCollection.SelectedValue)
Use it with sqlcommand parameter
if(ddl_collection.selectedvalue!="None")
command.Parameters.AddWithValue("#CollectionID", Convert.ToInt16(ddlcollection.selectedValue));
else
command.Parameters.AddWithValue("#CollectionID", DBNull.Value);
Related
I have a field in my table (Mssql database), "Name (Varchar(20)) NULL)"
How to read the field, which can be Empty or null?
I do like this:
if (myReader["Name"] != DBNull.Value || myReader["Name"] !=String.Empty)
Is there a built-in c# function to check it ?
(IsNullOrEmpty() ?? It doesn't check Database NULL type ?)
You must test DBNull.Value obligatory
IsNullOrEmpty test null value C# and empty, but not check null Database like DBNull.Value
I want a value to be set to NULL if nothing is put into the text box in the form I'm submitting. How can I make this happen?
I've tried inserting 'NULL' but this just adds the word NULL into the field.
I'm not sure what code I should provide for this, I'm just writing an UPDATE query.
Don't put NULL inside quotes in your update statement. This should work:
UPDATE table SET field = NULL WHERE something = something
You're probably quoting 'NULL'. NULL is a reserved word in MySQL, and can be inserted/updated without quotes:
INSERT INTO user (name, something_optional) VALUES ("Joe", NULL);
UPDATE user SET something_optional = NULL;
UPDATE MyTable
SET MyField = NULL
WHERE MyField = ''
You should insert null, not the string of 'NULL'.
Use NULL (without the quotes around it).
UPDATE users SET password = NULL where ID = 4
if (($_POST['nullfield'] == 'NULL') || ($_POST['nullfield'] == '')) {
$val = 'NULL';
} else {
$val = "'" . mysql_real_escape_string($_POST['nullfield']) . "'";
}
$sql = "INSERT INTO .... VALUES ($val)";
if you put 'NULL' into your query, then you're just inserting a 4-character string. Without the quotes, NULL is the actual null value.
Assuming the column allows a null setting,
$mycolupdate = null; // no quotes
should do the trick
The answers given here are good but i was still struggling to post NULL and not zero in mysql table.
Finally i noted the problem was in the insert query that i was using
$quantity= "NULL";
$itemname = "TEST";
So far so good.
My insert query was bad.
mysql_query("INSERT INTO products(quantity,itemname)
VALUES ('$quantity','$itemname')");
I corrected query to read.
mysql_query("INSERT INTO products(quantity,itemname)
VALUES ('".$quantity."','$itemname')");
So the $quantity is outside of the main string.
My sql table now accepted to record null quantity instead of 0
The problem you had is most likely because mysql differentiates between null written in capital letters and null written in small case.
So if you used an update statement with null, it would not work. If you set it to NULL, it would work fine.
Thanks.
I have code that creates a Null parameter like this
p = cmd.CreateParameter();
p.DbType = DbType.Int32;
p.ParameterName = strName;
p.Value = DBNull.Value;
cmd.Parameters.Add(p);
when I insert a record the SQLValue is set to {Null}
And the record is properly created with a Null value for the column.
When I select a record to try and retrieve a record with a Null value setting the parameter using the same approach above..once again the SQLValue for the parameter is {Null}
So same code same set up...but now it does not return the record. I cant retrieve any records when I want to create a parameter with a null value (p.Value = DBNull.Value;) . I get nothing back.
I know its not the query because if I change the parameter to one with a value I get that record back. Is there something I am missing to set the parameter to look for a null value? Everything I have seen has said to just do it that way.
As requested below is the query
Select * from view_full_class_nests
where parent_interface_class_pk = #parent_interface_class_pk
Also as noted this query works fine if the paramter is set with a value...only fails to retrieve if the value is DBNull.Value
DanD below provided useful link that gave me my answer
Need the query to be Select * from view_full_class_nests
where parent_interface_class_pk = #parent_interface_class_pk or #parent_interface_pk Is Null
You can't compare NULL in your where clause:
From https://msdn.microsoft.com/en-us/library/ms172138(v=vs.100).aspx:
Because null is considered to be unknown, two null values compared to each other are not considered to be equal. In expressions using arithmetic operators, if any of the operands is null, the result is null as well.
You will have to use ISNULL operator, see below for a previous answer that may help you:
Null value parameters in where clause in ado.net
I searched the entire web. I wonder why this easy task is so hard to accomplish in C#.
sqlcmd.Parameters.Add("#someid", System.Data.SqlDbType.UniqueIdentifier).Value =
string.IsNullOrEmpty(class.someid) ? System.Data.SqlTypes.SqlGuid.Null : new Guid(class.someid);
This returns an error :
Failed to convert parameter value from string to guid
My stored procedure updates a record in the table with the parameters relayed by C#.
What I want to do is to update a record and its specific column with null value by using a stored procedure which passes a guid parameter from C# with guid that can sometimes be null in value. Is this possible in C#?
Could you try:
sqlcmd.Parameters.Add("#someid", System.Data.SqlDbType.UniqueIdentifier).Value =
string.IsNullOrEmpty(class.someid) ? System.Guid.Empty : new Guid(class.someid);
If the casting doesn't work. And in your table make sure if this column allows null.
And class.someid has the correct format for the constructor.
You can check on this link to have an overview.
If I am not wrong, your column ID is of Guid type in your database, but your parameter is string.
You can convert your parameter to SqlGuid
command.Parameters.Add("#GuidParameter", SqlDbType.UniqueIdentifier).Value = new System.Data.SqlTypes.SqlGuid(YourGuid); //The value of #ID
Link : http://msdn.microsoft.com/fr-fr/library/system.data.sqltypes.sqlguid.aspx
Also try the following in the stored procedure:
Declare #someid uniqueidentifier = null
Declaring nullable property:
public Guid? column1;
Assigning Null:
column1 = null;
I'm getting values from database to a aspx page. while getting values of one column, the column is throwing a value like...
null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,
2391,2964,2965,2392,2393,2394,2395,2397
Now it throws a exception
Conversion failed when converting the varchar value 'null' to data
type int.
But I want all the other values of the column except the null...
Is there any way to convert this 'null' to '0', but still all the other values should exist.
Make your data type Nullable<int> instead of int to allow the converted int nullable values, or on the sql select statement you can do that: ISNULL(yourcolumn, 0) to convert null to 0.
I would just declare my type as int? variable; which is a nullable int type.
That would avoid you getting the exception, and you could easily convert your value to 0 if needed
if (value == null)
value = 0;
Since you say you want all of the values except the null value in your results, you could filter it in your select statement with a where clause.
SELECT * FROM COLUMN WHERE COLUMN_VALUE IS NOT NULL
Or, if you're using Linq to EF:
from x in yourObjectContext.yourColumns where x != null
I think you are trying to change from NULL to 0 in the database.
Then you should try this-
SELECT CASE WHEN columnName IS NULL THEN '0' ELSE columnName END FROM tableName