datetime? passing null in SQL when not entered

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

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 Web Forms
ASP.NET Web Forms
A part of the ASP.NET web application framework that can be used to create ASP.NET web applications.
390 questions
ASP.NET MVC
ASP.NET MVC
A Microsoft web application framework that implements the model-view-controller (MVC) design pattern.
582 questions
{count} votes

Accepted answer
  1. answered 2023-01-19T03:07:39.1533333+00:00
    Lan Huang-MSFT 8,876 Reputation points Microsoft Employee

    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.

    No comments

5 additional answers

Sort by: Most helpful
  1. answered 2023-01-18T10:40:46.5766667+00:00
    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ı.'

    No comments

  2. answered 2023-01-18T12:06:58.4633333+00:00
    Naimish Makwana 90 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.

    Thanks


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

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

    you should update the project to 4.8 first.

    No comments

  4. answered 2023-01-18T10:33:06.54+00:00
    Harun Ergün 65 Reputation points

    User's image

    For Example

    No comments