Question

I have a textbox that represents a date and I want to parse it to a DateTime, but sometimes this textBox can be empty string and I want to send it to the DataBase as null or as empty Date, how can I do it? I am using a webservice and I thought the following would pass a null:

txtCommentDateCreateNote.Text != string.Empty ? DateTime.Parse(txtCommentDateCreateNote.Text) : DateTime.MinValue,

but it returns the

"SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM."

ASP.NET and c# code below:

protected void cmdSaveCreateNote_Click(object sender, EventArgs e)
{
    ShortSaleInvestorReviewServiceClient _service = new ShortSaleInvestorReviewServiceClient();
    int createApp;

    createApp = _service.AddNote("10002",txtCommentDateCreateNote.Text != string.Empty ? DateTime.Parse(txtCommentDateCreateNote.Text) : DateTime.MinValue, 2, txtNoteCreateNote.Text); //Created by ID 
}
Was it helpful?

Solution

You attempted to pass the DateTime.MinValue, 1/1/0001 12:00:00 AM, which is a common technique. You discovered, however, that SQL Server datetime type does not like dates prior 1753.

DateTime is a structure and cannot be null. However, a nullable version is available. You can declare it like so...

DateTime? anullableDateTime;

If the .AddNote method has a nullable DateTime parameter, you are all set. Just set a null like so...

txtCommentDateCreateNote.Text != string.Empty ? DateTime.Parse(txtCommentDateCreateNote.Text) : null

If not, decide on a minimum date you will treat as null in your UI. 1/1/1900 is a favorite, and do this...

 txtCommentDateCreateNote.Text != string.Empty ? DateTime.Parse(txtCommentDateCreateNote.Text) : new DateTime(1900,1,1)

Just set your textbox.Text = null when you retrieve this value. Saving a real date has the added advantage of not having to deal with nulls in your database queries.

OTHER TIPS

Try This One

string.IsNullOrEmpty(txtCommentDateCreateNote.Text) ? (DateTime?)null : DateTime.Parse(txtCommentDateCreateNote.Text);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top