Atul
Atul

Reputation: 155

how to add null date into access database using c#

i want to insert null date into access database, if user select payment option as cash then cheque_date value should automatically enter as null if user not provide bill then bill_date should be enter as null in database iam trying to do this but Data type mismatch in criteria expression exception is coming for bill|_date and cheque_date im using masked textbox and for chequeno. and bill no. im using textbox(checkno and billno. its can be store as empty only problem is storing null date into accessc database)

if (txtchequeno.Text == "")
                {
                    cmd.Parameters.AddWithValue("@Cheque_No", cheque);
                }
                else
                {

                    cmd.Parameters.AddWithValue("@Cheque_No", txtchequeno.Text);
                }





            DateTime chequeDate;
            var value = (object)DBNull.Value;
            if (DateTime.TryParseExact(txtmaskchequedate.Text, "dd/mm/yyyy", null, System.Globalization.DateTimeStyles.None, out chequeDate))
            {
                value = chequeDate;
            }
            cmd.Parameters.AddWithValue("@Cheque_Date", value);  

 if (txtbillno.Text == "")
                {
                    cmd.Parameters.AddWithValue("@Bill_No", billno);

                }
                else
                {
                    cmd.Parameters.AddWithValue("@Bill_No", txtbillno.Text);


                }


              DateTime billdate;
            var value1 = (object)DBNull.Value;
            if (DateTime.TryParseExact(txtmaskbilldate.Text, "dd/mm/yyyy", null, System.Globalization.DateTimeStyles.None, out billdate))
            {
                value1 = billdate;
            }
            cmd.Parameters.AddWithValue("@Bill_Date", value1); 

here im change my code but still same error showing me Data type mismatch expression not getting still how to solve

Upvotes: 0

Views: 1236

Answers (1)

Atul
Atul

Reputation: 155

i set format : shortdate for cheque_date field in access database and here executed following code which is executed successfully either field having value or not(thank you @phils and @corak)

DateTime chequeDate;
                    var value = (object)DBNull.Value;
                    if (DateTime.TryParseExact(txtmaskchequedate.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out chequeDate))
                    {
                        value = chequeDate;
                    }


                    cmd.Parameters.AddWithValue("@Cheque_Date", value);

Upvotes: 0

Related Questions