code_junkie

What is the best way to deal with DBNull's

Nov 10th, 2011
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. DataRow row = ds.Tables[0].Rows[0];
  2. string value = (string)row;
  3.  
  4. int? value = 5;
  5.  
  6. DataRow row = ds.Tables[0].Rows[0];
  7. string value = row as string;
  8.  
  9. DataRow row = ds.Tables[0].Rows[0];
  10. string value;
  11.  
  12. if (row["fooColumn"] == DBNull.Value)
  13. {
  14. value = string.Empty;
  15. }
  16. else
  17. {
  18. value = Convert.ToString(row["fooColumn"]);
  19. }
  20.  
  21. return row["MyCol"] == DBNull.Value ? -99 : Convert.ToInt32(Row["MyCol"]);
  22.  
  23. Object.ID = DataReader["ID"] == DBNull.Value ? -99 : Convert.ToInt32(DataReader["ID"]);
  24. Object.Name = DataReader["Name"] == DBNull.Value ? "None" : Convert.ToString(DataReader["Name"]);
  25. Object.Price = DataReader["Price"] == DBNull.Value ? 0.0 : Convert.ToFloat(DataReader["Price"]);
  26.  
  27. string value = (
  28. from row in ds.Tables[0].Rows
  29. select row.Field<string>(0) ).FirstOrDefault();
  30.  
  31. SELECT
  32. ISNULL(name,'') AS name
  33. ,ISNULL(age, 0) AS age
  34. FROM
  35. names
  36.  
  37. // Or if (row["fooColumn"] == DBNull.Value)
  38. if (row.IsNull["fooColumn"])
  39. {
  40. // use a null for strings and a Nullable for value types
  41. // if it is a value type and null is invalid throw a
  42. // InvalidOperationException here with some descriptive text.
  43. // or dont check for null at all and let the cast exception below bubble
  44. value = null;
  45. }
  46. else
  47. {
  48. // do a direct cast here. dont use "as", "convert", "parse" or "tostring"
  49. // as all of these will swallow the case where is the incorect type.
  50. // (Unless it is a string in the DB and really do want to convert it)
  51. value = (string)row["fooColumn"];
  52. }
  53.  
  54. if (row.IsNull["fooColumn"])
  55. {
  56. value = string.Empty();
  57. }
  58. {
  59. else
  60. {
  61. value = row["fooColumn"].ToString;
  62. }
  63.  
  64. DataRow row = ds.Tables[0].Rows[0];
  65. string value;
  66.  
  67. if (row["fooColumn"] == DBNull.Value)
  68. {
  69. value = string.Empty;
  70. }
  71. else
  72. {
  73. value = Convert.ToString(row["fooColumn"]);
  74. }
  75.  
  76. DataRow row = ds.Tables[0].Rows[0];
  77. string value = row.ToString()
Add Comment
Please, Sign In to add comment