Validate that DataTable cell is not null or empty - c#

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

Related

String Comparison Error when Searching Blank Fields

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;

A better way to write null reference with return value in c#

Is there a better way to write this null check? I'm checking a table from a DataSet for nulls.
if (dataSet == null || dataSet.Tables == null || dataSet.Tables[0].Rows == null)
{
Console.WriteLine($"Error at {nameof(dataSet)}");
return vatPeriodList;
}
I'm working in ADO.NET.
Your check doesn't make sense and also forgets one important.
DataSet.Tables also can't be null because it's a readonly property, you can't assign null, so the second check is pointless.
dataSet.Tables[0].Rows can't be null because it's a readonly property, you can't assign null, so the last check is redundant.
But you forgot that the DataSet could be empty, so doesn't contain any DataTables. In that case your if throws an exception at dataSet.Tables[0].
I would use:
int? firstTablesRowCount = dataSet?.Tables.Cast<DataTable>().FirstOrDefault()?.Rows.Count;
if (firstTablesRowCount.GetValueOrDefault() == 0)
{
Console.WriteLine($"Error at {nameof(dataSet)}");
}
This ensures that the DataSet isn't null and contains tables and that the first table contains rows.
Try
if(dataSet?.Tables?.FirstOrDefault()?.Rows == null) {}
FirstOrDefault() returns the first entry or null if there is none.

Check for null value in DataGrid View Field when Assigning Variable

I'm trying to assign a value to a string variable when making a change to a datagridview field. Unfortunately if it's blank, it crashes with a NullReferenceException even if I try to check if it's null. I also don't know of a more efficient way to write this.
string change = "";
if (dgGroups[cid, rid].Value.ToString() != null) //gets null reference exception if row/column is blank.
{
change = dgGroups[cid, rid].Value.ToString();
}
Your check should be like this. You are trying to call null.ToString() which is not valid and it will throw NullReferenceException .
string change = "";
if (dgGroups[cid, rid].Value != null)
{
change = dgGroups[cid, rid].Value.ToString();
}
If you are using C# 6.0 you can write
string change = dgGroups[cid, rid].Value?.ToString();//this will return null if Value is null
You can use the ?? operator:
change = (dgGroups[cid, rid].Value ?? defaultValue).ToString();

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"]

C# DataTable ItemArray returns '{}' - how can I test for null value?

I have a DataTable resultSet; - I'm trying to check fields for null, but get an '{}' (empty-set ?) object back. Searches involving "{}" aren't yielding any appropriate solutions.
This is the code that isn't working as expected when the "fk_id" field is null:
if (resultSet.Rows[0].ItemArray[resultSet.Columns.IndexOf("fk_id")] == null)
{
//never reaches here
}
Note: using an int index instead of the Columns.IndexOf() isn't the issue.
Also does the "{}" have some other name in C#?
To check a column for DBNull in a DataSet, you can use the IsNull method:
if (resultSet.Rows[0].IsNull("fk_id"))
Your comparison against null is probably failing because DataSets don't use null to represent a "database NULL" value - they use DBNull.Value. If you need your code to work the way you've presented it, try this:
if (resultSet.Rows[0].ItemArray[resultSet.Columns.IndexOf("fk_id")] == DBNull.Value)
try
{
if (DT.Rows[0][0] != null)
{
//your code
}
}
catch
{
MessageBox.Show("AUTHANICATION FAILED.");
}
Please use:
dataTable.Select("FieldName is NULL")
this will give you the DataRows with null values in FieldName column.

Categories

Resources