Dataset comparison with Null Value c# - c#

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)

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

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

Best practice of SingleOrDefault()

I want to make my code better. Can I safely rewrite the first example to the second?
IQueryable<PDF> pdfList = (from pdfobj in pdfDataContext.PDFs
where pdfobj.Id == pdfId
select pdfobj);
if (pdfList.Count() > 0)
{
PDF pdfOldWay = pdfList.FirstOrDefault();
pdfOldWay. // do something. (pdfOldWay can't be null here...)
}
--
PDF pdfNewWay = (from pdfobj in pdfDataContext.PDFs
where pdfobj.Id == pdfId
select pdfobj).SingleOrDefault();
if (pdfNewWay != null)
{
// do something
}
--
EDIT:
Sorry for not being clear. My issue is to get the PDF object out directly without having to use a list first. I don't want to make a check for count is greater than 0 and because it just doesn't look good.
Yes, that looks safe. You can also simplify your query slightly:
PDF pdfNewWay = pdfDataContext.PDFs.SingleOrDefault(p => p.Id == pdfId);
if (pdfNewWay != null)
{
// do something
}
The only difference between SingleOrDefault and FirstOrDefault is that SingleOrDefault will throw an exception if more than one match is found, so unless you want this check then you may as well stick to FirstOrDefault.
You should use FirstOrDefault in the second case too as SingleOrDefault will throw an exception if there is more than one item. Is that ok for you?
On the other hand if you want to guarantee that there is only one pdfobject for some id than using SignleOrDefault is better.
If it's guaranteed that it always has 0 or 1 rows, then sure, SingleOrDefault is the best solution.
Yes you will achieve the same result, I don't see any issue.

what to check for when a datareader might not have a particular column?

I am doing a null check but I am getting a index of out range exception when doing:
if(myReader["column1"] != null)
{
}
Under certain conditions that column will not be present, why isn't a null check working?
Check to see if the column exists first
for(int i = 0; i < myReader.FieldCount; i++)
if (myReader.GetName(i) == "column1")
return true;
You want something like:
if (myReader.GetSchemaTable().Columns.Contains("ColumnName"))
{
}
Why is your query changing the columns that it is returning? Referencing the column using the name of the column throws the exception because the column index that corresponds to the name of the column is not found. If I were you I'd capture the exception and handle the error accordingly.
you might try GetSchemaTable()
If the same query returns different columns depending on stuff, doesn't look like a very good design to me. Anyway, you can use myReader.GetName(i) on the column that might be different to check whether you got the right column or not.
Well, the DataReader will expose a GetSchemaTable() which will give you the schema/columns within the DataReader.
Another alternative is to just attempt to grab the value from a column and catch the resulting exception, should that column not exist:
try
{
object value = dataReader["ColumnName"];
// Do something with the value...
}
catch(IndexOutOfRangeException e)
{
// Column not there!
}
However, I wouldn't advise this as throwing/catching exception is expensive business and should be truly reserved for something exceptional happening within your code.
I think the best thing is to use the GetSchemaTable() function but "roll-your-own" DoesColumnExist style function, something like:
public bool DoesColumnExist(IDataReader reader, string columnName)
{
reader.GetSchemaTable().DefaultView.RowFilter = "ColumnName= '" + columnName + "'";
return (reader.GetSchemaTable().DefaultView.Count > 0);
}

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