Searching through a column in a spreadsheet I notice that the second line will exception ("Nullable object must have a value.") when it comes across a blank field, however the first line will succeed. I have to add the Bool cast to the second line because otherwise I get "Cannot convert Nullable<bool> to bool". I assume this is the issue, but is there a way around that to allow blank fields to be checked?
keyFoundCell = _ws.Cells["a:a"].FirstOrDefault(cell => cell.Value?.ToString() == field.Key);
keyFoundCell = _ws.Cells["a:a"].FirstOrDefault(cell => (bool)cell.Value?.ToString().Equals(field.Key, StringComparison.OrdinalIgnoreCase));
In both EPPlus and Excel Interop you can read a cell's contents using the Text property instead of the Value property if you want to operate on the cell's visible contents and avoid nulls. Value returns an object which might be null, but Text returns the visible text as a string which can be empty but won't be null.
If we're using Value.ToString() or Value?.ToString() then chances are we'd be better off with Text because that's a giveaway that we want the text we see, not the value.
What's happening here is that the ?. operator will return null right away if the left hand side of the operator is null.
So, when cell.Value is null, the first line works because you're doing a direct comparison using the == operator, which will return a bool. In other words, null == field.Key returns false (unless field.Key is null, of course).
The second line does not work without a cast because if the value is null, then the ?. operator returns null and the rest of the line is ignored (.ToString() is never called). So the exception you're getting is due to the fact that the if condition must return a bool, yet it's returning a Nullable<bool> instead.
One way to fix this is to simply check for null first. This will not compare any objects where cell.Value == null:
keyFoundCell = _ws.Cells["a:a"].FirstOrDefault(cell =>
cell.Value != null &&
cell.Value.ToString().Equals(field.Key, StringComparison.OrdinalIgnoreCase));
Another way you can do this is to use the static Equals method of the string class, which will allow one or more null arguments. This will include results where cell.Value == null (and will return true for those cases where field.Key is also null):
keyFoundCell = _ws.Cells["a:a"].FirstOrDefault(cell =>
string.Equals(cell.Value?.ToString(), field.Key, StringComparison.OrdinalIgnoreCase));
maybe try:
keyFoundCell = _ws.Cells["a:a"].FirstOrDefault(cell => (bool?)cell.Value?.ToString().Equals(field.Key, StringComparison.OrdinalIgnoreCase)) ?? false;
Related
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()))
I have an object where a property may exist or may not exist.
if(response.AddressInformation.AddressResponses.Any(inf => inf.AddressResponse.matchCodeStatus.ToLower().Equals("usps_match")))
{
}
I have two array items of AddressResponse. First item has null for matchCodeStatus and thats where I get object not set to an instance exception. How can I achieve my target and escape this exception?
I tried to put a null check before my IF, but it didnt work
if(response.AddressInformation.AddressResponses.Any(inf => inf.AddressResponse.matchCodeStatus != null)
As of C# 6, you can also use a null conditional operator ?. :
inf => inf.AddressResponse.matchCodeStatus?.ToLower().Equals("usps_match"))
I am trying to check if there is at least one Textbox is not null as shown below but that condition will be true if all Textboxare not null not only one at least
foreach (TextBox cont in GB_Search.Controls.OfType<TextBox>())
{
if (string.IsNullOrEmpty(cont.Text))
{
// at least one control
}
}
You can use Linq for this.
The following will check that at least one should not be null and will return true if at least one text box contains value in it:
var oneHasValue = GB_Search.Controls.OfType<TextBox>()
.Any(x=>!string.IsNullOrEmpty(x.Text));
and the following would return true if all are not null or empty:
var allContainValue = GB_Search.Controls.OfType<TextBox>()
.All(x=>!string.IsNullOrEmpty(x.Text));
System.Windows.Controls TextBox
The default value of the TextBox.Text property is an empty string, so unless you've explicitly set it as null I don't see why you'd want to check for nullity.
You're most likely looking to see if any of the TextBox.Text is empty like this:
var result = GB_Search.Controls.OfType<TextBox>()
.Any(textBox => textBox.Text.Length == 0);
or if there is any non-empty:
var result = GB_Search.Controls.OfType<TextBox>()
.Any(textBox => !(textBox.Text.Length == 0));
Note - I've specifically used the Length property of the TextBox to check if it's empty as opposed to String.IsNullOrEmpty, this is simply because as mentioned above TextBox.Text is by default an empty string and as you've mentioned in the comments section under your post you're not explicitly setting it to null, thus there's no need to use String.IsNullOrEmpty as it performs a redundant check that you don't need.
System.Windows.Forms TextBox
Looking to see if any of the TextBox.Text is null or empty:
var result = GB_Search.Controls.OfType<TextBox>()
.Any(textBox => string.IsNullOrEmpty(textBox.Text));
or if there is any non null and non empty:
var result = GB_Search.Controls.OfType<TextBox>()
.Any(textBox => !string.IsNullOrEmpty(textBox.Text));
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"]
I have the following code which seems to blow up if the column in the datarow (dr) is null. what is the correct way to parse out the value from the data row and handle null checks?
Person person = new Person()
{
FirstName = dr["FirstName"].ToString(),
LastName = dr["LastName"].ToString(),
BusinessPhoneNumber = dr["BusinessPhone"].ToString(),
If the column is of type string, but is nullable, what about trying:
// FirstName must allow null
FirstName = dr["FirstName"] as string
or
// FirstName would be empty for a NULL in the database
FirstName = (dr["FirstName"] as string) ?? string.Empty
I believe, the data cell beeing null cannot be the reason for your problem. Maybe the column doesn't exist, or any other error happened, or the DataRow itself is null and you should handle that. Look at the exception - "seems to blow up" is not a valid description of your problem.
The following explains that, but will also answer the question from the title for everyone else.
If the column value is null, an object System.DBNull is returned, and .ToString() returns an empty string, while (string) or as string return null.
So it makes no sense to check the returned item for ==null because that won't ever evaluate to true.
If you accept empty strings as result, your code is already optimal, no need to handle the DBNull case.
If you want to get null, change .ToString() to as string.
If you want to handle it in any other way, use if (dr.IsNull("FirstName")) or do ==null on the target variable after the as string.
dr["FirstName"].ToString() will occasionally throw null pointer exceptions because you're trying to access ToString on a null object. Other than that, strings can be null, so really, if you know it's a string, and you don't mind that it's null, it'd be safe to do
FirstName = (String) dr["FirstName"]
Pass the column, and a default value to a helper function that checks for null and returns the default if null, or the column value if not null.
You can use the following to return a blank string if the column is null.
FirstName = string.format("{0}", dr["FirstName"])