Spent the most of easter digging through heaps of sql. So here's another “in-stinker” which almost had me fooled again.
Inside of a component I'm not afraid to work directly with sqlcommands. Setting up a datadapter and a dataset would be an overkill when the database will return just a scalar value. The result returned by the ExecuteScalar method can be somewhat misleading at first sight. Take this code
public string CustomerName(int custId)
{
SqlCommand cmd = new SqlCommand(string.Format("SELECT Name FROM Customers WHERE idCust = {0}", custId), sqlConnectionToSchaakBondDB);
object result = cmd.ExecuteScalar();
if (result == null)
return "Customer not found";
if (result == System.DBNull.Value)
return "Customer found but name is null";
return (string) result;
Testing the result only against null could give a quite misleading result. In the second case the method does return a value but the content of this value is null. Which is not the same as not returning a value at all.
Peter