Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Null Value to 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:

Object of type 'System.DBNull' cannot be converted to type 'System.String'.

The error occurs because one of the fields in the database has no value (null), so the string property could not handle it. How can i convert this null to string?

I got this solution

If you know a shorter or better one, feel free to post it. I'm trying to avoid checking on every loop is current value is null or not.

like image 841
peace Avatar asked Aug 24 '26 11:08

peace


1 Answers

Ben Got it almost right (I actually think it's just a "typo" from his side but I can't edit it for him). This should do the trick.

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

And you need to test en every iteration, since it's the value in a given cell in a given row there's really no way to avoid checking every one of those cell values before they are used

like image 165
Rune FS Avatar answered Aug 27 '26 00:08

Rune FS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!