Question

I have got this code below which care whether maskedtextbox is empty. If it is empty it INSERT INTO SQL table __.__.____ - only the mask so I believe it INSERTS NULL But something got wrong when I fill the maskedtextbox. It still INSERT __.__.____ - NULL I don't know where I make mistake because it should normally insert the date which is in the maskedtextbox.

The mask for this textbox is __.__.____ like 00/00/0000

Data type in which I insert this data is - date.

Here is the code:

var value2 = (object)DBNull.Value;
DateTime parsedDate2;
if (DateTime.TryParseExact(maskedTextBox2.Text, "__.__.____", null,
                           DateTimeStyles.None, out parsedDate2))
{
    value2 = parsedDate2;
}
prikaz.Parameters.AddWithValue("@odjdate", value2);

Edit : This code below says: the name 'value2' does not exist in the current context'

var value2 = (object)DBNull.Value;
DateTime parsedDate2;
if (DateTime.TryParseExact(maskedTextBox2.Text, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate2))
{
    value2 = parsedDate2;
}
prikaz.Parameters.AddWithValue("@odjdate", value2);

This code below does this Ex:

Converting into data type date wasn't succesfull.

This is the code

if (maskedTextBox2.Text == "__.__.____")
{
    prikaz.Parameters.AddWithValue("@odjdate", null);
}
else
{
    prikaz.Parameters.AddWithValue("@odjdate",maskedTextBox2.Text);
}
Was it helpful?

Solution

This works fine for me:

 var value2 = (Object)DBNull.Value;
 DateTime parsedDate2;
 if (DateTime.TryParse(maskedTextBox1 .Text, out parsedDate2))
 {
   value2 = (Object)parsedDate2;
 }
prikaz.Parameters.AddWithValue("@odjdate", value2);     

OTHER TIPS

Try this

var value2 = (object)DBNull.Value;
DateTime parsedDate2;
if (DateTime.TryParseExact(maskedTextBox2.Text, "dd.MM.yyyy", CultureInfo.InvariantCulture,DateTimeStyles.None, out parsedDate2))
{
    value2 = parsedDate2;
}

Note: if your format is "MM.dd.yyyy" then replace format to make the parse to work!

This should work

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top