Home > Net >  Simple validation of null data and converting it to integer in a DataRow object
Simple validation of null data and converting it to integer in a DataRow object

Time:08-26

I have code that is repeated in several parts of the project where I need to validate if the data is different from null and at the same time convert it into an integer for validation.

Is there a better way to get the same result with less code repetition?

Code example:

DataTable dtData = ReturnData();

foreach (DataRow row in dtData.Rows)
{
    if ((row["columnName"] != DBNull.Value) && (int.Parse(row["columnName"].ToString()) == 7))
    {
        //...
    }
}

CodePudding user response:

You could look at creating an extension method on DataRow. Something like this:

public static class DataRowExtensions
{
    public static bool IsColumnValidInteger(this DataRow row, string columnName, int expectedValue)
    {
        var columnValue = row[columnName];

        if (columnValue == DBNull.Value)
            return false;

        if (int.TryParse(columnValue.ToString(), out var parsedIntValue))
            return parsedIntValue == expectedValue;

        return false;
    }
}

This would let you write code like this:

DataTable dtData = ReturnData();

foreach (DataRow row in dtData.Rows)
{
    if (row.IsColumnValidInteger("columnName", 7)
    {
        //...
    }
}
  •  Tags:  
  • c#
  • Related