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,270 questions
{count} votes

Accepted answer
  1. Lan Huang-MSFT 25,716 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-19T05:14:54.3366667+00:00

    I found the solution. I practiced my every move

    if (cnvrt["lisansBaslamaTarih"].Value<string>() != "")

    af.LisansBaslangicTarih = cnvrt["lisansBaslamaTarih"].Value<DateTime?>();

    Thanks for Helping

    0 comments No comments