如何使“日期"字段将Null插入数据库? [英] how can i make Date field insert Null into the database?
问题描述
嗨.
我已在VS2010中为BirthDate的文本框之一中编写了一条插入语句,我已在SQlserver 2008r2中为其指定了日期类型,
我在该字段的代码(参数输入)在下面:
Hi.
i have written an insert statement In VS2010 , in one of textbox which is for BirthDate , i have assigned Date type for it in SQlserver 2008r2,
and my code(parameter input) for that field is in below:
cmd.Parameters.Add("@BirthDate_M", SqlDbType.Date).Value = Convert.ToDateTime(BirthDateTextBoxMilad.Text);
每当我在文本框内不写任何日期时,就会出现此异常:
字符串未被识别为有效的DateTime.
虽然我希望每当我不在textbox中写任何东西时,都将Null插入数据库,所以我写了这段代码:
whenever i don''t write any date inside textbox this exception appears:
String was not recognized as a valid DateTime.
while i want that whenever i don''t write anything in textbox , Null to be inserted into the Database, so i wrote this code:
cmd.Parameters.Add("@BirthDate_M", SqlDbType.Date).Value = null;
但是如果我这样做,将会出现另一个异常:
参数化查询``(@FirstName nvarchar(5),@ LastName nvarchar(5),@ FatherName nvarch''需要未提供的参数``@BirthDate_M''.
but if i do this , another exception will appear:
The parameterized query ''(@FirstName nvarchar(5),@LastName nvarchar(5),@FatherName nvarch'' expects the parameter ''@BirthDate_M'', which was not supplied.
which indicate that i have to insert a date.how can i prevent this happens and make it insert Null into the database.
推荐答案
hi,
试试这个,
try this,
cmd.Parameters.Add("@BirthDate_M", SqlDbType.Date).Value = (BirthDateTextBoxMilad.Text.Trim()==string.empty) ? DbNull.value : Convert.ToDateTime(BirthDateTextBoxMilad.Text.Trim());
希望它能起作用
hope it works
试试这个:
Hi,
Try this:
DateTime? value = Convert.ToDateTime(BirthDateTextBoxMilad.Text);
if (value.HasValue)
{
cmd.Parameters.Add("@BirthDate_M", SqlDbType.Date).Value = value;
}
--Amit
--Amit
尝试一下
try this
cmd.Parameters.Add("@BirthDate_M", SqlDbType.Date).Value = DBNull.Value;
这篇关于如何使“日期"字段将Null插入数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!