datetime? passing null in SQL when not entered

Harun Ergün 65 Reputation points


User's image


User's image

User's image


User's image

SQL Server

User's image

Opened Form

User's image

The user may or may not enter a Date.

The program runs when the user enters the date. But when it doesn't I get an error.

How can I leave the date field blank? So if the user doesn't want to enter Date, I want it to be Null or empty in SQL. ?????
A set of technologies in the .NET Framework for building web applications and XML web services.
3,238 questions
{count} votes

Accepted answer
  1. Lan Huang-MSFT 25,231 Reputation points Microsoft Vendor

    Hi @Harun Ergün,

    You can try this: DateTime? dt = string.IsNullOrEmpty(date) ? (DateTime?)null : DateTime.Parse(date);

    It is not clear how you save the data to the database, you can refer to the following to add DBNull.Value.

    cmd.Parameters.AddWithValue("@Date", (object)dt ?? DBNull.Value);

    Best regards,
    Lan Huang

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

5 additional answers

Sort by: Most helpful
  1. Harun Ergün 65 Reputation points

    @Olaf Helper When I passed Datetime? null my code give me massege "System.FormatException: 'Dize geçerli bir DateTime olarak tanınmadı.'

    1 person found this answer helpful.
    0 comments No comments

  2. Naimish Makwana 170 Reputation points

    Please check the Request object value in the HomeController action.

    In case of empty date text box, You might get some invalid value in request and code is not able to convert that Date formate to Valid Date.


    1 person found this answer helpful.

  3. Bruce ( 54,626 Reputation points

    you are using too old of a runtime to support DateTime?

    you should update the project to 4.8 first.

    1 person found this answer helpful.
    0 comments No comments

  4. Harun Ergün 65 Reputation points

    User's image

    For Example

    0 comments No comments