From what I gather you have two potential problems:
- The record is found but the return value from the database is
NULL
- The record isn't found.
In the latter case a c#
null
value is returned but in the first case a
DBNull.Value Field (System) | Microsoft Docs[
^] would be returned.
If in both cases you want to return null, you could modify the method
GetScalarValue
to return the following
return value == DBNull.Value ? null : value ;
Then what comes to handling the null value in method
GetFee
, if the fee would be NULL I would imagine you want to show an empty string. After all a fee of 0 is different from the situation when a fee is not found.
If the assumption is correct you could use nullable int. In other words
private int? GetFee()
{
int? fee;
...
fee = (int?)db.GetScalarValue...
...
return fee;
}
Also you would need to change the calling code to the following to avoid null reference exception
FeeLabel.Text = GetFee();
A little off-topic but it seems that you're storing the connection in some variable, perhaps even in open state. I would recommend not to do this. Instead, keep the connection open as short time as possible and let connection pooling to handle repeated connection opens, for more information, see
SQL Server Connection Pooling (ADO.NET) | Microsoft Docs[
^]