How to display DBNull int as blank - c#

I am selecting information from a database of mostly strings, however I have a datatype of number which if that value in the db is null I would like it to display as blank in my grid. I've tried reading the number in as a string but it is not working.
AccountUid = dr["ACCOUNT_UID"] == DBNull.Value ? null: Convert.ToInt32(dr["ACCOUNT_UID"])
I'm not sure what to put in where null is to get a db value of null to display as nothing. AccountUid is an int?.

Below is how I got it to work. So I was close I just needed to add (int?) to null and it works now.
AccountUid = dr["ACCOUNT_UID"] == DBNull.Value ? (int?)null : Convert.ToInt32(dr["ACCOUNT_UID"])

Related

Validate that DataTable cell is not null or empty

I would like to check if the value in a Data Table cell is either null or empty/blank space. The String.IsNullOrEmpty() method does not work as the row["ColumnName"] is considered an object.
Do I need to do a compound check like the following or is there something more elegant?
if (row["ColumnName"] != DBNull.Value && row["ColumnName"].ToString().Length > 0)
{
// Do something that requires the value to be something other than blank or null
}
I also thought of the following ...
if (!String.IsNullOrEmpty(dr["Amt Claimed"].ToString()))
{
// Do something that requires the value to be something other than blank or null
}
but I figured if the value of the cell was null an exception would be thrown when trying to convert to a string using ToString()
A null value would be returned as DBNull, and not a null literal.
var tab = new System.Data.DataTable();
tab.Columns.Add("c1");
tab.Rows.Add();
tab.Rows[0]["c1"] = null;
tab.Rows[0]["c1"].GetType() //returns DBNull
And as the DBNull.ToString() is guaranteed to return an empty string, you can safely use !String.IsNullOrEmpty(value.ToString())).
You can always guard against not being sure if an object is null by simply using null coalescing.
!String.IsNullOrEmpty(value?.ToString()))

cannot insert null for date using dictionary

I'm trying to insert record using C# and SQL, but i got this error when date column is empty, i searched for a similar cases but didnt solve it yet. It inserts 01/01/1900, the column in table is Datetime any idea or similar case link.
[HttpPost]
public HttpResponseMessage save (Education edu)
{
Dictionary<string, object> xmt = new Dictionary<string, object>();
xmt.Add("#Staff_Key", edu.Staff_Key);
xmt.Add("#Type_Education", edu.Type_Education);
xmt.Add("#Qual", edu.Qual);
xmt.Add("#Uni", edu.Uni);
xmt.Add("#Date_Issue", edu.Date_Issue.ToString() == null ? "Null" : edu.Date_Issue.ToString());
xmt.Add("#Notes", edu.Notes);
obj.ExecNonQuery(
#"insert into HR_DocEducation (Staff_Key,Type_Education,Qual,Uni,Date_Issue,Notes)
values (#Staff_Key,#Type_Education,#Qual,#Uni,#Date_Issue,#Notes) ",xmt);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
return response;
Hassan,
I had the same issue, the trick in addition to use the nullable DateTime DateTime? object is correcting the ternary operator as follows:
xmt.Add("#Date_Issue", edu.Date_Issue == null ? (object) DBNull.Value : (object)edu.Date_Issue);
instead of
xmt.Add("#Date_Issue", edu.Date_Issue.ToString() == null ? "Null" : edu.Date_Issue.ToString());
As said by Astha Srivastava, you can find a short description of DateTime's behavior on null values.
Question: DateTime “null” value
A possible way is to use the propertie DBNull.Value which is referencing to a value used on databases. I can recommend to use that when using SQL Commands.
After a short lookup I found a similar question of yours, using the DBNull.Value as example. Look it up and if it might help you give the answer a upvote.
Question: Nullable DateTime and the Database

Insert empty params into decimal nullable columns

I have no values to insert into MaxPrice or MinPrice columns which can be null. The values when they don't exist are originally were seen as , , in the resulting Sql expression. I got a syntax error before and changed the code to this
(setItem.MinPrice.ToString()!="")?setItem.MinPrice.ToString() : null,
(setItem.MaxPrice.ToString() != "") ? setItem.MaxPrice.ToString() : null
But when I execute this I get an error and the sql still looks like the , , . The columns are decimal but can be NULL.
Use parameters. Always.
cmd.Parameters.AddWithValue("#minPrice",
setItem.MinPrice == null ? DBNull.Value : (object)setItem.MinPrice);
cmd.Parameters.AddWithValue("#maxPrice",
setItem.MaxPrice == null ? DBNull.Value : (object)setItem.MaxPrice);
or with a tool like Dapper:
// adds "#MinPrice" and "#MaxPrice" correctly as parameters, as long
// as the sql contains those tokens in some way
conn.Execute(sql, new { setItem.MinPrice, setItem.MaxPrice });
The bad fix - do not use - would be to supply the literal "null" in your concatenation. There are many many reasons not to do this:
// bad code; do not use
(setItem.MinPrice.ToString() != "") ? setItem.MinPrice.ToString() : "null",
(setItem.MaxPrice.ToString() != "") ? setItem.MaxPrice.ToString() : "null"

How to return a null value from a database

I am trying to populate a combobox with a list my query returns. When I execute my program it gives me a specified cast is not valid error ( I have it execute on page load event). Every field in the database I have to work with can be null except the primary key. So I tried using DBNull.Value but it can't get my (int)reader fields to work. I have supplied my code below for a better understanding. How can I get my (int)reader's to work with my statements, so they can read when there is a null value?
CustData cd = new CustData();
cd.CustomerID = (int)reader["CustomerID"];
cd.Name = reader["Name"] != DBNull.Value ? reader["Name"].ToString() : string.Empty;
cd.ShippingAddress = reader["ShippingAddress"] != DBNull.Value ? reader["ShippingAddress"].ToString() : string.Empty;
cd.ShippingCity = reader["ShippingCity"] != DBNull.Value ? reader["ShippingCity"].ToString() : string.Empty;
cd.ShippingState = reader["ShippingState"] != DBNull.Value ? reader["ShippingState"].ToString() : string.Empty;
cd.ShippingZip = (int)reader["ShippingZip"];
cd.BillingAddress = reader["BillingAddress"] != DBNull.Value ? reader["BillingAddress"].ToString() : string.Empty;
cd.BillingCity = reader["BillingCity"] != DBNull.Value ? reader["BillingCity"].ToString() : string.Empty;
cd.BillingState = reader["BillingState"] != DBNull.Value ? reader["BillingState"].ToString() : string.Empty;
cd.BillingZip = (int)reader["BillingZip"];
cd.Territory = reader["Territory"] != DBNull.Value ? reader["Territory"].ToString() : string.Empty;
cd.Category = reader["Category"] != DBNull.Value ? reader["Category"].ToString() : string.Emptyy
That is because int is not nullable. You need to use int? or nullable<int> (long hand) to allow it to be an int OR a null value.
You can then use the usual .HasValue and .Value etc to get the value from the item.
EDIT: To enhance the visibility of my comment to this answer. I would advise against checking for NULL and storing Zero into your property because then when you save back you are changing a Null to a Zero even though nothing has been changed by the system. Now, reports etc may distinguish between NULL and Zero (very often) and could start doing strange things!
Null does NOT equal zero!! If you assume it does as a work around... What happens if I truly do want to record zero? How do you differentiate between a real zero and a "was null now zero" trick? Do it right, save yourself the pain!
Use nullable int, or just make your control for your int's too
reader["ShippingZip"] != DBNull.Value ? (int)reader["ShippingZip"] : default(int);
You should use a nullable int for your variable and cast it, like (int?). Int can only have a value; nullable types can also be null. When you use a nullable type, you can look at the property .HasValue. Here is the MSDN page: http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx

DataRow: Check for empty (Not "null) fields in DataSet

Hopefully this is an easy one. Is there a way to test for an "empty" field using DataRow? The following work fine for testing against a field with null values, unfortunately, the column I'm dealing with are either populated with data or are just "empty". Is there an approach in C# I'm missing? Thanks
if (Particle.Tables.Count == 0 || pDr.ItemArray[1].ToString() == "")
tblParticle.Append("No Data");
you can use stirng.isNullorEmpty to check for empty fields. String.isNullorEmpty
if (Particle.Tables.Count == 0 || string.isNullorEmpty(pDr.ItemArray[1].ToString()))
{
tblParticle.Append("No Data");
}
.
if (string.IsNullOrEmpty(pDr.ItemArray[1].ToString()))
{
tblParticle.Append("No Data");
}
else
{
//else do something else
}
checking for NULL will not hurt keep in mind that Null and Empty are two different things
See DataRow.IsNull method - it accepts a column name or index
and returns whether it is NULL
The following assumes we are talking about a string (VARCHAR/CHAR) column:
If you don't care if it is null or an empty string, and always want an empty string back, you can use DataRow["name"].ToString()
If you want your string object to become null or empty just like the field value, you can use DataRow["name"] as string
If you want to get an exception in case of NULL, you can use (string) DataRow["name"]

Categories

Resources