简体   繁体   中英

check the dataset for null values

i want to check all my data set for null values and replace them. in order to do it i wrote this code:

public static DataSet Validator(DataSet dataSet)
{
    foreach (DataTable dataTable in dataSet.Tables)
    foreach (DataRow dataRow in dataTable.Rows)
    foreach (DataColumn dataDataColumn in dataTable.Columns)
    if (dataRow[dataDataColumn] == DBNull.Value)
    {
        if (dataRow[dataDataColumn].GetType() == typeof(string)) 
            dataRow[dataDataColumn] = "";
        else if (dataRow[dataDataColumn].GetType() == typeof(DateTime))
            dataRow[dataDataColumn] = DateTime.MinValue;
        else if (dataRow[dataDataColumn].GetType() == typeof(int) ||
                 dataRow[dataDataColumn].GetType() == typeof(short) ||
                 dataRow[dataDataColumn].GetType() == typeof(long) ||
                 dataRow[dataDataColumn].GetType() == typeof(float) ||
                 dataRow[dataDataColumn].GetType() == typeof(byte) ||
                 dataRow[dataDataColumn].GetType() == typeof(double)) 
            dataRow[dataDataColumn] = 0;
    }

    return dataSet;
}

but it doesn't work!. where is the problem? and if there is a better way i really appreciated to let me know. Thank you.

UPDATE but it doesn't work!. still there is null values in the dataset.

When you run

dataRow[dataDataColumn].GetType()

you call GetType() on the value of dataRow[dataDataColumn] , which is always DBNull.value . So you always get the type DBNull .

Check for dataDataColumn.DataType instead, which will return the actual datatype of the column.


You could use something like:

public static DataSet Validator(DataSet dataSet)
{
    foreach (DataTable dataTable in dataSet.Tables)
        foreach (DataRow dataRow in dataTable.Rows)
            foreach (DataColumn dataDataColumn in dataTable.Columns)
                if (dataRow.IsNull(dataDataColumn))
                    dataRow[dataDataColumn] = GetDefaultValue(dataDataColumn.DataType);

    return dataSet;
}

static object GetDefaultValue(Type t)
{
    // get the default value for value types
    if (t.IsValueType)
        return Activator.CreateInstance(t);

    // in case of a string, we want an empty one instead of null
    if (t == typeof(string))
        return String.Empty;

    return null;
}

You are using DBNull.Value to check for null values, try testing it against Null as well.

There is a difference between DBNull.Value and Null as previously explained here What is the difference between null and System.DBNull.Value?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM