I am working with an application that reads multiple dates from an Oracle database and assigns it to DateTimePickers
.
dtpAdjSerDt.Value = dr.GetDateTime(iadj_service_date);
However, this assignment requires a null check as the values in the db could be null
.
I would like to be able to create an extension method that returns a default value if the value is null.
public static DateTime fSafeGetDateTime(OracleDataReader reader, int colIndex)
{
if (!reader.IsDBNull(colIndex))
return reader.GetDateTime(colIndex);
else
return DateTime.Now;
}
There is one problem with this approach: If the db value is null then the DateTimePicker.Checked should be false. But using the strategy I suggested above it would be set to true.
Is there a way for me to do something like this:
public static DateTime fSafeGetDateTime(OracleDataReader reader, int colIndex, DateTimePicker control)
{
if (!reader.IsDBNull(colIndex))
return reader.GetDateTime(colIndex);
else
{
control.Checked = false;
return DateTime.Now;
}
}
If this is not possible what would be the cleanest way (avoiding duplicate code) to accomplish this?
I suggest you just return a DateTime?
and let the caller do the defaulting:
public static DateTime? SafeGetDateTime(this OracleDataReader reader, int colIndex)
{
return reader.IsDBNull(colIndex) ? null
: (DateTime?) reader.GetDateTime(colIndex);
}
Now you can use:
DateTime fromReaderOrNow = reader.SafeGetDateTime(1) ?? DateTime.Now;
And if you need the control part:
DateTime? fromReader = reader.SafeGetDateTime(1);
if (fromReader == null)
{
control.Checked = false;
}
DateTime fromReaderOrNow = fromReader ?? DateTime.Now;
If you really need to do that in multiple places, you can wrap up a method to do - and you won't be repeating the SafeGetDateTime
code.
(I would encourage you to separate our your database code further from your UI code to start with, to be honest.)