how to insert null date value in database using asp.net 3 tier architecture

if (objChildFees.childid != null)
{
        objChildFees.classstudentid = 0;
        objChildFees.classid = Convert.ToInt16(ddlClass.SelectedValue);
        objChildFees.centerid = Convert.ToInt32(Session[CommonVariables.gCentreId].ToString());
        objChildFees.roomno = 1;
        objChildFees.startdate = Convert.ToDateTime(txtStartDate.Text.ToString());
        objChildFees.enddate = Convert.ToDateTime(txtEndDate.Text.ToString());
        objChildFees.newfees = Convert.ToDecimal(txtfeesamt.Text.ToString());
        objChildFees.feestype = chkFeesPay.Checked == true ? 1 : 2;
        objChildFees.childdaystype = chkfulltime.Checked == true ? 1 : 2;
        objChildFees.feepermonthforsubsidized = 0;
        objChildFees.feepermonthforpartime = 0;
        objChildFees.feepermonthforparttimesubsidized = 0;
        objChildFees.activestatus = true;
        objChildFees.withdrawaldate = Convert.ToDateTime(txtwtdate.Text);
}

How to add null withdrawal date in this code I am facing the error: String was not recognized as a valid DateTime

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If objChildFees.withdrawaldate can be null, you can set it as a nullable DateTime. Check the value of txtwtdate.Text before attempting to convert it to a DateTime?

public class ChildFees 
{
  // The ? after DateTime indicates this variable should be a nullable datatype
  DateTime? withdrawldate {get; set;}
  ...
}

objChildFees.withdrawaldate = string.IsNullOrWhiteSpace(txtwtdate.Text) ? null : (DateTime?)Convert.ToDateTime(txtwtdate.Text);

In a production system, you would likely want to use DateTime.TryParse to make sure the value of txtwtdate.Text contains a valid date string when converting to avoid exceptions thrown during conversion.

Method 2

public static class Extenstions
{
    public string ToNullableString(this string value)
    {
         if (string.IsNullOrEmpty(value))
         {
             return null;
         }
         
         return value;
     }
}

Make sure that withdrawaldate property is has a nullable type (DateTime?)

Then used like this Convert.ToDateTime(txtwtdate.Text.ToNullableString())


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x