Marek
Marek

Reputation: 3575

MaskedTextbox unable to insert NULL date into SQL

I have maskedtextbox which inserts date into SQL data type date. IN SQL it has NULLs allowed but if I try to insert this maskedtextbox empty. It gives an error that it is unable to convert symbols into Date data type. This maskedtextbox is like ..__ (DD.MM.YYYY)

My Parameter for INSERT INTO SqlCommand is this:

   prikaz.Parameters.AddWithValue("zodjdate", maskedTextBox2.Text);

How should I change it to make it insert NULLs?

Thanks in advance. M.S.

Upvotes: 1

Views: 702

Answers (1)

Andomar
Andomar

Reputation: 238086

var value = (object) DBNull.Value;
DateTime parsedDate;
if (DateTime.TryParseExact(maskedTextBox2.Text, "dd.MM.yyyy", null, 
                           DateTimeStyles.None, out parsedDate))
{
    value = parsedDate;
}
prikaz.Parameters.AddWithValue("zodjdate", value);

Upvotes: 3

Related Questions