datetime? passing null in SQL when not entered

Harun Ergün 65 Reputation points
2023-01-18T08:58:00.6233333+00:00

HomeController.cs

User's image

AnketForm.cs

User's image

User's image

Index.cshtml

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. ?????
ASP.NET
ASP.NET
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
    2023-01-19T03:07:39.1533333+00:00

    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
    2023-01-18T10:40:46.5766667+00:00

    @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
    2023-01-18T12:06:58.4633333+00:00

    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.

    Thanks

    1 person found this answer helpful.

  3. Bruce (SqlWork.com) 54,626 Reputation points
    2023-01-18T19:40:11.5633333+00:00

    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
    2023-01-18T10:33:06.54+00:00

    User's image

    For Example

    0 comments No comments