Click here to Skip to main content
13,004,099 members (114,052 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I have a database MS 2007 with various data types of columns. I am binding this database to a datatable in C#. i want to write data from a textbox to a particular column in the main database whose type is date time . the difficulty is that every time I have to enter a valid datetime value in the text box column before writing it to the database. if it do not have a valid datetime it create error.

what i want is that i should be able to write to the database column from the textbox even when the value of text box is null. i dont want to keep any default value in the datetime column of database when the text box is null.

I use the following code
Projects.dt.Rows[j]["DATERECEIVED"] = txtDTR.Text;
Projects.dt.Rows[j]["DATEDISPATCHED"] = txtDTD.Text;
                    Projects.da = new OleDbDataAdapter(Projects.cmdstring, Projects.connection);
                    Projects.cmdb = new OleDbCommandBuilder(Projects.da);                    
                    DialogResult result;
                    result = MessageBox.Show("Do you Want To Save ", "", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                        if (Projects.dt.GetChanges() != null)

thanks in advance
Posted 25-Oct-11 22:06pm
Updated 25-Oct-11 22:10pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Use DBNull.Value.

Try as below code.
if (string.IsNullOrEmpty(txtDTR.Text))
  Projects.dt.Rows[j]["DATERECEIVED"] = DBNull.Value;
  Projects.dt.Rows[j]["DATERECEIVED"] = txtDTR.Text;
if (string.IsNullOrEmpty(txtDTD.Text))
  Projects.dt.Rows[j]["DATEDISPATCHED"] = DBNull.Value;
  Projects.dt.Rows[j]["DATEDISPATCHED"] = txtDTD.Text;
MohammadIqbal 26-Oct-11 4:27am
thanks it works
RaisKazi 26-Oct-11 4:32am
Perfect.! Please do not forget to "Accept Answer", so that it can be a reference solution for some one else.
Mehdi Gholam 26-Oct-11 4:34am
my 5!
RaisKazi 26-Oct-11 4:34am
Thank you Mehdi. :)
Member 10920951 6-Jan-16 9:37am
The Answer you posted above is not working.
RaisKazi 6-Jan-16 10:14am
Whats not working? And whats the issue u facing?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170627.1 | Last Updated 26 Oct 2011
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100