Insert null value to Sql server bigInt column - c#

A table contain bigInt column named 'Phone' I want to insert null value to this column by entity frame work. I used following codes:
objRegister.Phone = Convert.ToInt64(txtPhone.Text ??null );
But i get this message: "Input string was not in a correct format.".
I change the code as shown in below:
objRegister.Phone = txtMobile.Text != null ?Convert.ToInt64(txtMobile.Text):((long?)null) ;
I got same message : "Input string was not in a correct format."

You could try this something like this:
long phone;
objRegister.Phone = long.TryParse(txtPhone.Text, out phone)
? (long?)phone
: (long?)system.DBNullValue;

Int64 phoneNumber;
Int64.TryParse(txtPhone.Text, out phoneNumber) == true ? phoneNumber : DBNull.Value;
You can use ?: Conditional Operator with Int64.TryParse check whether text is convertible to Int64. If convertible then assign convertible value else DBNull.Value

Related

How to retrieve data from sql database to check boxes [duplicate]

In C#, using SqlDataReader, is there a way to read a boolean value from the DB?
while (reader.Read())
{
destPath = reader["destination_path"].ToString();
destFile = reader["destination_file"].ToString();
createDir = reader["create_directory"].ToString();
deleteExisting = Convert.ToBoolean(reader["delete_existing"]);
skipIFolderDate = reader["skipifolderdate"].ToString();
useTempFile = reader["useTempFile"].ToString();
password = reader["password"].ToString();
}
In the code above, delete_existing is always a 1 or 0 in the DB. I read on MSDN that Convert.ToBoolean() does not accept a 1 or 0 as valid input. It only accepts true or false. Is there an alternative way to convert a DB value to a bool? Or do I need to do this outside of the SqlDataReader?
Also, I can not change the DB values, so please no answers saying, "Change the DB values from 1's and 0's to true's and false's."
Thanks!
If the type of delete_existing is a sqlserver 'bit' type, you can do :
var i = reader.GetOrdinal("delete_existing"); // Get the field position
deleteExisting = reader.GetBoolean(i);
or (but it will crash if delete_existing can be DBNull)
deleteExisting = (bool)reader["delete_existing"];
or better, this onebelow is DBNull proof and returns false if the column is DBNull
deleteExisting = reader["delete_existing"] as bool? ?? false;
Otherwise if the database type is int :
deleteExisting = (reader["delete_existing"] as int? == 1) ? true : false;
or if it is a varchar
deleteExisting = (reader["delete_existing"] as string == "1") ? true : false;
Casting works:
myVar = (bool)dataReader["myColumn"];
How about this?
deleteExisting = (reader["delete_existing"] as int?) == 1;
Boolean is probably the easist type to convert something to. Here's the 'Y', 'N' version:
deleteExisting = string.Equals(reader["delete_existing"] as string, "Y", StringComparision.OrdinalIgnoreCase);
If you are using CASE in SELECT and want to use GetBoolean then use CAST to change the column to bit before reading.
For eg:
SELECT CAST((CASE WHEN [Condition] THEN 1 ELSE 0 END) as bit) FROM Table_Name
then you can use
reader.GetBoolean(0)
deleteExisting = reader.GetBoolean(reader["delete_existing"]);

How to send a Null value in xml string

The RefNo column in SQL Server table is of datatype bigint, and can accept Nulls.
I am saving multiple records via xml using c#. The code works good, but for a few records, the RefNo has to be null, and it is saving as 0 even when I comment the 'else' part in stringbuilder.
SQL:
ALTER PROCEDURE SaveActivity
#XMLData xml
AS
BEGIN
IF #XMLData IS NOT NULL
BEGIN
CREATE TABLE #Temp(
ActivityId uniqueidentifier,
RefNo int,
Notes nvarchar(500)
);
INSERT INTO tblActivityDetails(ActivityId,RefNo,Notes)
SELECT
detail.query('ActivityId').value('.','uniqueidentifier') as ActivityId,
detail.query('RefNo').value('.','int') as RefNo,
detail.query('Notes').value('.','nvarchar(500)') as Notes
FROM
#XMLData.nodes('/details/detail') AS xmlData(detail)
END
END
C#:
StringBuilder sb = new StringBuilder();
sb.AppendLine("<?xml version=\"1.0\"?>");
sb.AppendLine("<details>")
foreach(GridViewRow gr in gvActivity.Rows)
{
HiddenField hdRefNo = (HiddenField)gr.FindControl("hdRefNo");
HiddenField hdNotes = (HiddenField)gr.FindControl("hdNotes");
string sRefNo = hdRefNo.value.ToString()=="0" ? null :
hdRefNo.value.ToString();
sb.AppendLine("<detail>");
sb.AppendLine("<ActivityId>"+ gActivityId.ToString() + "</ActivityId>");
if(sRefNo!="0")
sb.AppendLine("<RefNo>"+ sRefNo + "</RefNo>");
else
sb.AppendLine("<RefNo></RefNo>");
sb.AppendLine("<Notes>"+ hdNotes.value.ToString() + "</Notes>");
sb.AppendLine("</detail>");
}
sb.AppendLine("</details>")
You don't need to use query() when fetching values. Use values() directly and you will get NULL if the RefNo node is missing.
detail.value('(RefNo/text())[1]','int') as RefNo
Try using "" instead of null in
string sRefNo = hdRefNo.value.ToString()=="0" ? null :
hdRefNo.value.ToString();
like
string sRefNo = hdRefNo.value.ToString()=="0" ? "":
hdRefNo.value.ToString();
and remove if else part and just keep the statement
sb.AppendLine("<RefNo>"+ sRefNo + "</RefNo>");
In this line
string sRefNo = hdRefNo.value.ToString()=="0" ? null :
hdRefNo.value.ToString();
your checking string and if it equals "0" that assign null, so when you after try checking
if(sRefNo!="0") // this condition always true
sb.AppendLine("<RefNo>"+ sRefNo + "</RefNo>");
else
sb.AppendLine("<RefNo></RefNo>");
Possibly if you change condition to !string.IsNullOrEmpty(sRefNo) it will be work as expected
When you try get int field and in xml it don't set, then here
....
detail.query('RefNo').value('.','int') as RefNo,
....
will be return default value, i.e. 0
for solving you can try use number() function like this
....
detail.query('RefNo').value('number(.)','int') as RefNo,
....

EF 5.0 inserting null into smallint column

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);

Conversion failed when converting the varchar value 'null' to data type int

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

Read boolean values from DB?

In C#, using SqlDataReader, is there a way to read a boolean value from the DB?
while (reader.Read())
{
destPath = reader["destination_path"].ToString();
destFile = reader["destination_file"].ToString();
createDir = reader["create_directory"].ToString();
deleteExisting = Convert.ToBoolean(reader["delete_existing"]);
skipIFolderDate = reader["skipifolderdate"].ToString();
useTempFile = reader["useTempFile"].ToString();
password = reader["password"].ToString();
}
In the code above, delete_existing is always a 1 or 0 in the DB. I read on MSDN that Convert.ToBoolean() does not accept a 1 or 0 as valid input. It only accepts true or false. Is there an alternative way to convert a DB value to a bool? Or do I need to do this outside of the SqlDataReader?
Also, I can not change the DB values, so please no answers saying, "Change the DB values from 1's and 0's to true's and false's."
Thanks!
If the type of delete_existing is a sqlserver 'bit' type, you can do :
var i = reader.GetOrdinal("delete_existing"); // Get the field position
deleteExisting = reader.GetBoolean(i);
or (but it will crash if delete_existing can be DBNull)
deleteExisting = (bool)reader["delete_existing"];
or better, this onebelow is DBNull proof and returns false if the column is DBNull
deleteExisting = reader["delete_existing"] as bool? ?? false;
Otherwise if the database type is int :
deleteExisting = (reader["delete_existing"] as int? == 1) ? true : false;
or if it is a varchar
deleteExisting = (reader["delete_existing"] as string == "1") ? true : false;
Casting works:
myVar = (bool)dataReader["myColumn"];
How about this?
deleteExisting = (reader["delete_existing"] as int?) == 1;
Boolean is probably the easist type to convert something to. Here's the 'Y', 'N' version:
deleteExisting = string.Equals(reader["delete_existing"] as string, "Y", StringComparision.OrdinalIgnoreCase);
If you are using CASE in SELECT and want to use GetBoolean then use CAST to change the column to bit before reading.
For eg:
SELECT CAST((CASE WHEN [Condition] THEN 1 ELSE 0 END) as bit) FROM Table_Name
then you can use
reader.GetBoolean(0)
deleteExisting = reader.GetBoolean(reader["delete_existing"]);

Categories