How to insert null value for datetime field in asp.net? - asp.net

I am trying to insert null value from front end. This is my code:
if (!string.IsNullOrEmpty(txtCallTwo.Text))
{
DateTime second = DateTime.ParseExact(txtCallTwo.Text.Trim(), "MM/dd/yyyy", CultureInfo.InvariantCulture);
objclsConsultantLeadStatusProp.dtDate_2nd_Call = second;
}
else
{
DateTime second = DateTime.ParseExact(txtCallTwo.Text.Trim(), "MM/dd/yyyy", CultureInfo.InvariantCulture);
objclsConsultantLeadStatusProp.dtDate_2nd_Call = null;
}
dtDate_2nd_Call property is declared as as Datetime.

You need to make dtDate_2nd_Call as nullable property. Syntax for nullable property is like this.
DateTime? dt = null;
For your case it should be Datetime? dtDate_2nd_Call instead of Datetime dtDate_2nd_Call

The answer to this question is pretty simple. I am not sure if it is of any help to you now...
The DateTime data structure in .NET does not accept null values and thus gives you the error, the simple solution to this is adding a question mark without spaces next to DateTime, i.e., DateTime?
DateTime? data structure accepts null values and thus you won't get the error.

Related

FlexBuilder dateField '01/01/1901'

I've a dateField in FlexBuilder that returns DateTime from WebService C# and SqlServer.
The dateField show all DateTime from SqlServer, but with Date 'Null', It shows '01/01/1901'
What I need to do to get the datetime instead of null in date field.
You can handle this case on database layer so that all clients of this stored procedure / query will get same default value in case of null.
here's an example:
SELECT name, ISNULL (dateofbirth, GETDATE() ) FROM user
GETDATE() will return today's (server's system) date instead.
of-course not a reasonable default in above example, and you might want to do date manipulations for calculating some default value. you can use these reference docs
I solved problem :
public function IsDateNull(date:Date):String`enter code here`enter code here
{
if (date && date.fullYear == 1901)
{
return null;
}
else
{
return dateTimeFormatter1.format(date);
}
}
<s:DateTimeFormatter id="dateTimeFormatter1"
dateTimePattern="EEEE, dd MMMM , yyyy "
dateStyle="long" locale="it-IT"
errorText="Invalid input value"
useUTC="false"/>
<mx:DateField id="sData_ComunicazioneOSDateField" selectedDate="{classeDati.sData_ComunicazioneOS}" labelFunction="IsDateNull" />
Thank you for the help!!!

Format DateTime Data Display In Grid View

I am trying to retrieve DateTime data type data from database in Asp.Net. Here is the code:
DateTime date = DateTime.Parse(dr["packingDate"].ToString());
However, the problem is the date I retrieved display in such format : 26/11/2013 12.00 AM . I just wanted to display the date but not the time. I'd tried to do this:
DateTime date = DateTime.Parse(dr["packingDate"].ToString());
string dateStr = date.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
However, it does not works in my grid view. I wonder why is it so?
Thanks in advance.
Use the built-in to string function for jsut the Date value...
DateTime.ToShortDateString();
Select the corect type from database, so in this case datetime. Then you get a DateTime in your DataTable which you can cast with the DataRow's Field extension method:
DateTime date = dr.Field<DateTime>("packingDate");
If you only want to diplay the date:
string dateOnly = dr.Field<DateTime>("packingDate").ToShortDateString();
or
string dateOnly = dr.Field<DateTime>("packingDate").ToString("d");
or
string dateOnly = dr.Field<DateTime>("packingDate").ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
You could format on the GridView control, for sample:
<asp:BoundField DataField="packingDate" HeaderText="PackingDate"
DataFormatString="{0:dd-M-yyyy}" />

Dates Comparison in asp.net

I have two text boxes where i am populating them with calendar i,e I am getting dates into the textboxes in string format.
i,e string startdate=txtstartdate.text;
i,e string enddate=txtenddate.text;
now i need to compare these two dates.
my requirement is: enddata should be greaterthan startdate.
Kindly help me in this regard.
DateTime.TryParse is the safest way because it doesn't throw exceptions like DateTime.Parse. It returns true/false on the call so you can handle failures very simply.
string text1 = DateTime.Now.ToString();
string text2 = DateTime.Now.AddHours(-4).ToString();
DateTime d1;
if(!DateTime.TryParse(text1, out d1)) Console.WriteLine("Failed to parse text1");
DateTime d2;
if(!DateTime.TryParse(text2, out d2)) Console.WriteLine("Failed to parse text2");
if(d1 > d2) Console.WriteLine("d1 \"{0}\" is greater than d2 \"{1}\"", d1, d2);
else Console.WriteLine("d1 \"{0}\" is not greater than d2 \"{1}\"", d1, d2);
Also, I noticed several answers using Compare and I hardly ever use .Compare.
You need to parse them as dates and then compare them. Example:
DateTime sdate= DateTime.Parse(txtstartdate.Text);
DateTime edate = DateTime.Parse(txtenddate.Text);
if(sdate>edate)
{
Throw validation error;
}
Dim startDate As DateTime
Dim endDate As DateTime
Dim returnValue As Integer
returnValue = DateTime.Compare(startDate, endDate)
If returnvalue is:
Less than zero -> startDate is earlier than endDate.
Zero -> startDate is the same as endDate.
Greater than zero -> startDate is later than endDate.
if (DateTime.Parse(enddate).CompareTo(DateTime.Parse(startdate)) > 0) {
// enddate is later than startdate
}
That piece of code doesn't do any error checking. You may want to do error checking when parsing string into date.

Convert date as Integer in Codebehind

I've been searching around the net but I only see integer to date. How can I convert a chosen date in radDatePicker to integer? I have tried Convert.ToInt32 but I get an error at runtime
You can try this code
DateTime dt =Convert.ToDateTime(RadDatePicker1.SelectedDate);
string temp = dt.ToShortDateString();
int value;
int.TryParse(temp, out value);
Try this:
DateTime.Now.Ticks
For normal datetime object it works. Means if you could get DateTime value from radDatePicker you may apply .Ticks property to it.

Pass a NULL in a parameter to a DateTime field in a stored procedure

I have a stored procedure which updates a database using the parameters I supply but I'm having trouble passing a NULL to the stored procedure
The field I need to make NULL is a DateTime field
DB.Parameters.AddWithValue("#date", NULL)
This gives me the error
'NULL' is not declared. 'Null' constant is no longer supported; use 'System.DBNull' instead
So I tried
DB.Parameters.AddWithValue("#date", DBNull.Value.ToString())
But this produces the value 1900-01-01 00:00:00.000 in the column as it's passing a "" to the field
I also tried
DB.Parameters.AddWithValue("#date", DBNull.Value)
But it produces this error
Value of type 'System.DBNull' cannot be converted to 'String'.
Has anybody got any ideas?
Or you can add your parameter like this, which gives it a null value in the database if your variable is null:
DB.Parameters.AddWithValue("#date", myDateTime ?? (object)DBNull.Value);
you need to set it as a nullable type as Amit mentioned.
More details and background available at http://evonet.com.au/overview-of-c-nullable-types/
Try something like this, using Add rather than AddWithValue:
DB.Parameters.Add("#date", SqlDbType.DateTime).Value = DBNull.Value;
Try this
If you are using class and its property and those property values are used as parameter then you can do this
chnage the signature of the property to
public DateTime? myDateTime = null;// Here ? is used to make the property nullable.
Also if your date column is of type varchar then correct it to Date (Sql2008) / DateTime(2005).
//change parameter to this
#SomeDate datetime = null (as suggested by chris)
Allow the field to accept null and then pass the value as
DB.Parameters.Add("#date", DBNull.Value)
This is an example. It's work for me
if(obj.myDate == DateTime.MinValue)
{
aCommand.Parameters.Add("dateParameter", SqlDbType.Date).Value = DBNull.Value;
}
else
{
aCommand.Parameters.Add("dateParameter", SqlDbType.Date).Value = obj.myDate ;
}

Resources