Checking for Null values when accessing field values - c#

I am attempting to check a field value for null.
Assuming that item is a valid Outlook ContactItem, the following code, I would have thought, would have checked for a null value and returned "(Empty)" if the relevant field is null.
EntryID = item.EntryID.ToString() ?? "(nothing)";
Title = item.Title.ToString() ?? "(nothing)";
First_Name = item.FirstName.ToString() ?? "(nothing)";
Middle_Name = item.MiddleName.ToString() ?? "(nothing)";
Last_Name = item.LastName.ToString() ?? "(nothing)";
Suffix = item.Suffix.ToString() ?? "(nothing)";
Company = item.CompanyName.ToString() ?? "(nothing)";
Home_Phone = item.HomeTelephoneNumber.ToString() ?? "(nothing)";
Mobile_Phone = item.MobileTelephoneNumber.ToString() ?? "(nothing)";
FirstLastName= item.LastNameAndFirstName.ToString() ?? "(nothing)";
However, what is happening on other fields, is an error as follows:
Object reference not set to an instance of an object.
The error is not a NullReferenceException in the strict sense - the error relates to the contacts field not the ContactItem object.
Now would I be right in saying that the error is actually telling me that the field is in fact an object, which if it does contain text, is removed from the ContactItem ?
I have attempted to mitigate the error, by filling in each field in an Outlook Contact - the error does not get thrown - but if I delete the field contents, of say CompanyName, the code will fail on that line with the same error.
If I am right, then how would I check if the object exists prior to trying to get the field contents?
MTIA
DWE

Try using the null-conditional operator.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators
Example:
If Property is null:
EntryID = item.EntryID?.ToString() ?? "(nothing)";
If item is null:
EntryID = item?.EntryID.ToString() ?? "(nothing)";
Or check both
EntryID = item?.EntryID?.ToString() ?? "(nothing)";

Try Using Ternary Conditional Operator
Condition ? True : False
If you are retriving data from Database then this
if(item.EntryID.ToString() == DBNull) ? item.EntryID.ToString() : "(nothing)";
And if still shows error then try to put ? with datatype of EntryID
public string? EntryID;

Related

Dealing with empty cells when importing Excel file using EPPlus

I want to import data from Excel to DataBase using EPPLUS. From here I took code: https://www.paragon-inc.com/resources/blogs-posts/easy_excel_interaction_pt6
The problem is that sometimes in excel are empty Cells. And if cell is empty then I receive an error: NullReferenceException, and my application stops. I think good solution would be assign null value to specific variable if there is no reference e.g. if(LAST_NAME returns NullReferenceException then LAST_NAME = null) - but I don't know how to do this in code.
var newRecord = new DB_USER
{
ID = Int32.Parse(worksheet.Cells[idColumn + row].Value.ToString()),
FIRST_NAME = worksheet.Cells[firstNameColumn + row].Value.ToString(),
LAST_NAME = worksheet.Cells[lastNameColumn + row].Value.ToString() //If this value has NullReferenceException then assign null or ""
};
I thing its fine to assign a empty string i.e. string.Empty for empty cells .And if you are fine you can put it this way :
var newRecord = new DB_USER
{
ID = Int32.Parse(worksheet.Cells[idColumn + row].Value.ToString()),
FIRST_NAME = worksheet.Cells[firstNameColumn + row].Value.ToString(),
LAST_NAME = worksheet.Cells[lastNameColumn + row].Value ?? string.Empty).ToString() //for a null value assign a empty string else the string value
};
A cleaner approach would be Extension method :
public static string ToNullSafeString(this object obj)
{
return (obj ?? string.Empty).ToString();
}
and use it as :
LAST_NAME = worksheet.Cells[lastNameColumn + row].Value.ToNullSafeString();
still if you wish to return a null instead of string.Empty then a slight modification to ToNullSafeString extension method above will work.
If you are using the latest C# version (6.0) then you can use the null propagation operator:
LAST_NAME = worksheet?.Cells[lastNameColumn + row]?.Value?.ToString()

How to handle null values from SQLite DB with C#?

EDIT:
Thanks to everyone who replied! I appreciate all of your answers :)
So I have a class with the following constructor:
public Transaction(DataRow row)
{
LastName = row.Field<string>("LastName");
FirstName = row.Field<string>("FirstName");
MI = row.ItemArray[3].ToString()[0];
ContactNumber = row.ItemArray[4].ToString();
Hours = int.Parse(row.ItemArray[5].ToString());
CheckIn = (DateTime)row.ItemArray[6];
roomNumber = int.Parse(row.ItemArray[9].ToString());
//Paid = row.Field<int>("Paid");
//TotalBill = row.Field<int>("TotalBill");
}
Notice I have 2 of them commented out with /'s That's because if I don't they return null values even if I try ''row.Field([Whatever]).GetValueOrDefault()'', it still comes out null and my constructor returns null. I also have my DB set with default values so IDK what's wrong.
Anyone got a work around? :)
The DataRow class has a method that is called IsNull and that could receive the column name.
Just combine it with the conditional operator
Paid = row.IsNull("Paid") ? 0 : row.Field<int>("Paid");
the same is true for all other fields that could contain a null value.
Just check for null first and supply a default value:
public Transaction(DataRow row)
{
LastName = row.Field<string>("LastName");
FirstName = row.Field<string>("FirstName");
MI = row.ItemArray[3].ToString()[0];
ContactNumber = row.ItemArray[4].ToString();
Hours = int.Parse(row.ItemArray[5].ToString());
CheckIn = (DateTime)row.ItemArray[6];
roomNumber = int.Parse(row.ItemArray[9].ToString());
Paid = row.Field<int?>("Paid") ?? 0;
TotalBill = row.Field<int?>("TotalBill") ?? 0;
}
See the ?? Operator (C# Reference) page on MSDN for further information on the ?? operator.
You can simply use the Nullable type and GetValueOrDefault method or use null coalescing operator.
Paid = row.Field<int?>("Paid").GetValueOrDefault()
or
Paid = row.Field<int?>("Paid") ?? 0
In both cases Paid will have a value of 0, you can change if you want.
Create your own little function that does a simple check.
Along the lines of:
public integer GetNumber (object val)
{
if (IsNumeric (val))
{
return val;
} else
{
return 0;
}
}
I'm not fantastic with C#, but that should give you an idea. Sorry about formatting, I'm on a phone which doesn't help at all.

Update SQL with a null or int value

I want to be able to update the table from c# with either a null or int. The dropdown will either have an id as the selected value or empty string, if it's an empty string I want to pass a null otherwise I want the id. I've tried this but getting an error "Input string was not in a correct format." Can anyone help? Thanks
var result = (from p in dc.Prices where p.price_ID == Id select p).FirstOrDefault();
result.no_update = String.IsNullOrEmpty((grd.Rows[e.RowIndex].FindControl("ddlNoUpdate") as DropDownList).SelectedValue.ToString()) ? System.Data.SqlTypes.SqlInt32.Null.Value : int.Parse((grd.Rows[e.RowIndex].FindControl("ddlNoUpdate") as DropDownList).SelectedValue.ToString());
dc.SubmitChanges();
Try using this code, it worked for me once
String insertedVal = (grd.Rows[e.RowIndex].FindControl("ddlNoUpdate") as DropDownList).SelectedValue.ToString()
result.no_update = String.IsNullOrWhiteSpace(insertedVal)
? (object)DBNull.Value : (object)insertedVal

adding NULL to DropdownList-options

On my ASP.NET MVC4 application, I need a dropdown-list to select a Location and insert its ID into a table, say News.
Some news apply to ALL Locations - therefore the LocationID in News is Nullable, to indicate this.
So I need to add "ALL Locations" to the dropdown.
This is how I imagined, it would work - but on the last line Value = DBNull.Value (or simple null) is not allowed. It only accepts an integer. I CANNOT use "0" as foreign key constraints on that table do not allow 0, because there is no ID=0 in Locations-table
var locations = db.Locations.Select(c => new { DisplayText = c.Location, Value = c.ID }).ToList();
locations.Insert(0, new { DisplayText = "All Locations", Value = DBNull.Value });
return Json(new { Result = "OK", Options = locations});
How can I add this to the options-list?
The basis of your locations anonymous object is created in the new {} operator in your Linq statement. If you need to allow for NULL, then... new { DisplayText = c.Location, Value = (int?)c.ID } explicitly set the anonymous type's Value parameter as nullable int. Then you can do Value = null on the next line when inserting.

Linq and datetime validation

I am trying to insert a DateTime value in sqlserver using linq. The DateTime value in the csharp side may be null. The corresponding field in sqlserver is a nullable datetime field. Following is my code:
using (var dataContext = GetDataContext())
{
DateTime dateTime;
var combinedWorkBasket = new CombinedWorkBasket()
{
FirstName = combinedWorkbasketData.FirstName,
LastName = combinedWorkbasketData.LastName,
Address1 = combinedWorkbasketData.Address1,
RetirementDate = Convert.ToDateTime(combinedWorkbasketData.RetirementDate),
};
dataContext.CombinedWorkBaskets.InsertOnSubmit(combinedWorkBasket);
dataContext.SubmitChanges();
}
When combinedWorkbasketData.RetirementDate happens to be null, which is a string value, which could be a valid date or null, then sqlserver throws error saying the date should be within range. When combinedWorkbasketData.RetirementDate happens to be null, Convert.ToDateTime(combinedWorkbasketData.RetirementDate) translates to some invalide data value. I tried the following, still same issue.
RetirementDate = DateTime.TryParse(combinedWorkbasketData.RetirementDate, out temp) ? Convert.ToDateTime(combinedWorkbasketData.RetirementDate) : Convert.ToDateTime(null)
I simply want to accomplish the following: When combinedWorkbasketData.RetirementDate is a valid date insert RetirementDate, otherwise don't insert it but insert other values such as Firstname etc
Thanks
You might want to use a nullable data type, but this helps only if your database permits null values in the RetirementDate column. In addition, you must make the RetirementDate field in class CombinedWorkBasket nullable, too.
using (var dataContext = GetDataContext())
{
DateTime? dateTime;
var combinedWorkBasket = new CombinedWorkBasket()
{
FirstName = combinedWorkbasketData.FirstName,
LastName = combinedWorkbasketData.LastName,
Address1 = combinedWorkbasketData.Address1,
RetirementDate = combinedWorkbasketData.RetirementDate != null ?
Convert.ToDateTime(combinedWorkbasketData.RetirementDate) : null;
};
dataContext.CombinedWorkBaskets.InsertOnSubmit(combinedWorkBasket);
dataContext.SubmitChanges();
}
The problem is that datetime does not holds null value but it holds minimum time i.e. some thing like this. '1/1/0001 12:00:00 AM'.
Instead of directly passing the date time try using
DateTime.MinValue== Convert.ToDateTime(combinedWorkbasketData.RetirementDate)?Null:Convert.ToDateTime(combinedWorkbasketData.RetirementDate)
I have not tested the code use it as reference u might be needing some refinement.
I think RetirementDate must be of nullable type for Entity framework to insert DBNull.
So make it like
public class CombinedWorkBasket
{
// other fields
public DateTime? RetirementDate { get; set; }
}
Then try assigning Null as per logic with associated column as "Allow Null" in database.
Hopefully it will insert null.

Categories

Resources