challengeAccepted
challengeAccepted

Reputation: 7590

If TextBox has date Convert to DateTime else NULL

Is it possible to Convert a a Textbox value to datetime if the TextBox has value, else save as NUll in the database using the following way. This is VS 2005 using c# to save it to the SQL Server 2005.

I understand that i can check before hand if the textbox has date and then call this function. I have a function that saves other values into the db even if the date was not entered into the Textbox. This is just an example i was trying to give here

new BusinessLogic.BizLogic().InsertDate(CID, Convert.ToDateTime(txtDate.Text));

Thank you in advance.

Upvotes: 0

Views: 1221

Answers (2)

evanmcdonnal
evanmcdonnal

Reputation: 48096

Yes. But you need to pull the conversion logic outside of that statement.

 DateTime dt;

 if (!DateTime.TryParse(TextBox.text, dt))
      dt = null;

Upvotes: 0

Win
Win

Reputation: 62260

DateTime value;

new BusinessLogic.BizLogic().InsertDate(CID, 
DateTime.TryParse(txtDate.Text, out value) ? value : (DateTime?)null);

Upvotes: 3

Related Questions