peace
peace

Reputation: 887

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.

Upvotes: 3

Views: 25431

Answers (3)

ChrisF
ChrisF

Reputation: 137178

There's no solution other than checking for null where there's a dereference or method call.

If PropertyItem.Name can be null or PropertyItem.SetValue can't accept a null value then you have to check on every loop.

Upvotes: 1

Rune FS
Rune FS

Reputation: 21752

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

Upvotes: 5

Coding Flow
Coding Flow

Reputation: 21881

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);
    }

Upvotes: 0

Related Questions