中将空值写入datetime类型的数据库列

中将空值写入datetime类型的数据库列

本文介绍了在C#中将空值写入datetime类型的数据库列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MS 2007数据库,其中包含各种数据类型的列.我将此数据库绑定到C#中的数据表.我想将文本框中的数据写到主数据库中类型为date time的特定列中.困难在于,每次我必须在文本框列中输入一个有效的datetime值后,再将其写入数据库.如果没有有效的日期时间,则会创建错误.

我想要的是即使文本框的值为null,我也应该能够从文本框中写入数据库列.当文本框为null时,我不想在数据库的datetime列中保留任何默认值.

我使用以下代码

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);
                    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

推荐答案

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;
}


这篇关于在C#中将空值写入datetime类型的数据库列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 15:05