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"]
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()))
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;
I have a asp.net app where I utilize hidden fields to store values (if need be).
So on the designer side I have this..
<asp:HiddenField ID="hdDDAPDischargeDate" runat="server" />
In my C# code I either assign a value to it or leave it as is, so basically something along the lines...
if ( condition.........)
{
hdDDAPDischargeDate.Value.ToString()== '10/23/2017'
}
But in many cases I don't assign a value, so later on when i go to check what the value of it is, i can't get it to hit the ELSE part of the if statement
I tried:
if (hdDDAPDischargeDate.Value != null)
if (hdDDAPDischargeDate.Value.ToString != null)
But in both cases it thinks there's a value in the field, or I'm basically checking it wrong
If i hover over the field, it simply shows ""
Hidden fields can't be null, which makes sense if you think about the way they are represented in the HTTP request.
Try checking for an empty string instead:
if (hdDDAPAdmissionDate.Value != "")
{
//Foo
}
If for some reason you don't believe me or are not sure, you can always check both:
if (hdDDAPAdmissionDate.Value != null && hdDDAPAdmissionDate.Value != "")
{
//Foo
}
Or better yet:
if (!string.IsNullOrEmpty(hdDDAPAdmissionDate.Value))
{
//Foo
}
Goodday
I can't seem to use my dataset in a Null comparison
I'm trying to make an statement (attempts go below) where it will only continue my code when my dataset is empty.
Code 1:
if ((string)dts.Tables[0].Rows[0]["RECID"] != null)
^ just skips my if, I know that it's empty (checked my watch), still continues even when it is null.
Code 2:
long Recid = 0;
Boolean checkrecid = long.TryParse((string)dts.Tables[0].Rows[0]["RECID"], out Recid);
if (checkrecid == false)
^ Crashes at my Tryparse. I know you can use Trycatching, but I don't want to use it, cause it will make my program run slower, and it needs to read a good 10000 lines a day ...
Error:
A first chance exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll
Meaning that it can't find anything, but I know that already.
EDIT: I do not want an error. Any previous methods, who all work in other cases, return an indexoutofrange error. I'll add this ..
The dataset is filled with data from an SQL server based on phonenumbers and other data.
If he can't find the phonenumber, which comes from a text file, he will return nothing, no row, no column, nothing.
Thanks in advance,
DZ
You need to use DBNull.Value instead of null
EDIT: Index outside the bounds may mean there are no rows at all. Try replacing your if with this:
if (dts.Tables[0].Rows.Count > 0 && dts.Tables[0].Rows[0]["RECID"] != DBNull.Value)
{
}
This line:
if ((string)dts.Tables[0].Rows[0]["RECID"] != null)
needs to be
if ((string)dts.Tables[0].Rows[0]["RECID"] != DBNull.Value)
Or you could delete that check:
Boolean checkrecid = long.TryParse((dts.Tables[0].Rows[0]["RECID"] ?? string.Empty), out Recid);
if((string)dts.Tables[0].Rows[0]["RECID"] is DBNull)
{ // will go here }
Found it!
int strTables = dts.Tables[0].Rows.Count;
if (strTables == 1){ //code goes here}
A type-safe alternative is using Field extension method. It will return 'null' instead of DBNull.Value for empty fields.
if (dts.Tables[0].Rows[0].Field<string>("RECID") != null)
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.