- You call
String.ToString()
unnecessarily.
- Your code doesn't handle the case of non-empty, but invalid, input.
My version:
{
Object paramValue = DBNull.Value;
DateTime value;
if( DateTime.TryParse( txtInvoiceDate.Text, out value ) ) {
paramValue = value;
}
query.Parameters.AddWithValue("@InvoiceDate", SqlDbType.SmallDateTime).Value = paramValue;
}
Note my use of {}
anonymous scopes so the paramValue
and value
variables don't pollute the local scope.
If you find yourself doing this often, you can change it to a method:
static SqlParameter AddDateParameter(SqlCommand cmd, String parameterName, String inputValue) {
SqlParameter p = cmd.CreateParameter();
p.Name = parameterName;
p.SqlDbType = SqlDbType.SmallDateTime;
cmd.Parameters.Add( p );
DateTime value;
if( DateTime.TryParse( inputValue, out value ) ) {
p.Value = value;
}
else {
p.Value = DBNull.Value;
}
return p; // return `p` in case the caller wants to modify the parameter further
}
Used like so:
AddDataParameter( query, "@InvoiceDate", txtInvoiceDate.Text );
As an aside, it might be an idea to replace txtInvoiceDate
(which I assume is a TextBox
) with a DateTimePicker
control instead, which would outright prevent invalid input and also expose a strongly-typed DateTime
value directly, without the need to use DateTime.TryParse
.