Converting a null value to a string - C # .NET

    foreach (PropertyInfo PropertyItem in this.GetType().GetProperties())
    {
        PropertyItem.SetValue(this, objDataTable.Rows[0][PropertyItem.Name.ToString()], null);
    }

In one of the loops, I get this exceptional error:

An object of type System.DBNull cannot be converted to type System.String.

The error occurs due to the fact that one of the fields in the database does not have a value (null), so the string property cannot handle this. How can I convert this null to string?

I got this solution

If you know shorter or better, feel free to post it. I am trying to avoid checking in every loop whether the current value is null or not.

+3
source share
3 answers

. ( , "" , ). .

foreach (PropertyInfo PropertyItem in this.GetType().GetProperties())
    {
        var value = objDataTable.Rows[0][PropertyItem.Name.ToString()];
        PropertyItem.SetValue(this, value == DBNull.Value ? "" : value.ToString() , null);
    }

, .

+5

, null, .

PropertyItem.Name null PropertyItem.SetValue , , .

+1
foreach (PropertyInfo PropertyItem in this.GetType().GetProperties())
    {
        string strValue = objDataTable.Rows[0][PropertyItem.Name.ToString()] == DbNull.Value ? String.Empty : objDataTable.Rows[0][PropertyItem.Name.ToString()].ToString();
        PropertyItem.SetValue(this, strValue, null);
    }
0
source

Source: https://habr.com/ru/post/1746740/


All Articles