Click here to Skip to main content
15,899,586 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
C#
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);                    
                    Projects.da.Fill(Projects.dt);
                    Projects.dt.GetChanges();

                    DialogResult result;
                    result = MessageBox.Show("Do you Want To Save ", "", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {

                        if (Projects.dt.GetChanges() != null)
                        {

                            Projects.da.Update(Projects.dt);
                            Projects.connection.Close();

                        }
                        Projects.dt.AcceptChanges();
                    }


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

1 solution

Use DBNull.Value.

Try as below code.
C#
if (string.IsNullOrEmpty(txtDTR.Text))
{

  Projects.dt.Rows[j]["DATERECEIVED"] = DBNull.Value;
}
else
{
  Projects.dt.Rows[j]["DATERECEIVED"] = txtDTR.Text;
}

if (string.IsNullOrEmpty(txtDTD.Text))
{
  Projects.dt.Rows[j]["DATEDISPATCHED"] = DBNull.Value;
}
else
{

  Projects.dt.Rows[j]["DATEDISPATCHED"] = txtDTD.Text;
}
 
Share this answer
 
Comments
[no name] 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    
RaisKazi,
The Answer you posted above is not working.

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900