What is the best way to deal with DBNull's

后端 未结 14 1039
迷失自我
迷失自我 2020-12-02 15:45

I frequently have problems dealing with DataRows returned from SqlDataAdapters. When I try to fill in an object using code like this:



        
14条回答
  •  猫巷女王i
    2020-12-02 15:54

    DBNull implements .ToString() like everything else. No need to do anything. Instead of the hard cast, call the object's .ToString() method.

    DataRow row = ds.Tables[0].Rows[0];
    string value;
    
    if (row["fooColumn"] == DBNull.Value)
    {
       value = string.Empty;
    }
    else 
    {
       value = Convert.ToString(row["fooColumn"]);
    }
    

    this becomes:

    DataRow row = ds.Tables[0].Rows[0];
    string value = row.ToString()
    

    DBNull.ToString() returns string.Empty

    I would imagine this is the best practice you're looking for

提交回复
热议问题