简体   繁体   中英

Error: String was not recognized as a valid DateTime. I'm using jquery datepicker with asp.net and c# web forms and sql databse

I have a text box in which i select the date from the datepicker. I then need to validate: 1. A date is selected 2. date selected is not a future date. only todays date or any previous date. 3. Regular hrs add over time hours on that date do not exceed 20-24 hrs.

I've an error "Error: String was not recognized as a valid DateTime." Can I please get some help over this as I have spent days over this.

C# code:

protected void btnCreate_click(object sender, EventArgs e)
    {
        try
        {
            DateTime dt = DateTime.ParseExact(DateTxt.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces);

            if (DateTxt.Text != "" && PName_dd.Text != "" && CCG_dd.Text != "" && CCL_dd.Text != "")
            {

                cmd.CommandText = "INSERT INTO TSHistory(EmpId_Int, ProjectCode_Int, TSDate_dt, CCode_Int, TSRhours_nu, TSOhours_nu, JobDescp_vc) VALUES(@GEId, @Pcode, @date, @CCode, @Rhr, @Ohr, @job)";
                cmd.Parameters.AddWithValue("@GEId", EmpID.Text);

                cmd.Parameters.AddWithValue("@PCode", PCode_txt.Text);
                cmd.Parameters.AddWithValue("@date", dt);
                cmd.Parameters.AddWithValue("@CCode", CCL_dd.SelectedValue);
                cmd.Parameters.AddWithValue("@Rhr", R_txt.Text);
                cmd.Parameters.AddWithValue("@Ohr", O_txt.Text);
                cmd.Parameters.AddWithValue("@job", JobDesc_txt.Text);
                cmd.Parameters.AddWithValue("@Emp", EmpID.Text);
                cmd.Connection = Cnn;
                Cnn.Open();
                cmd.ExecuteNonQuery();
                Cnn.Close();
                updateUserDetails();
                // displayTS();
                RefreshSrc();
                RefreshDatabase();


            }

            else
            {


                //  DateTime dt = Convert.ToDateTime();
                //   var total_hrs = 24;
                //   DateTime dt = DateTime.ParseExact(DateTxt.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces);
                //   global.Text = "Done";

                if (DateTxt.Text == "")

                {
                    // Response.Write("<script>alert('PLease select date');</script>");
                    //  dateError.Text = "PLease select date";
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Select date')", true);



                }


                else if (DateTxt.Text != "" && dt > DateTime.Today)

                {
                    // Response.Write("<script>alert('Invalid Date');</script>");
                    //  dateError.Text = "Invalid date";
                    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Invalid date')", true);


                }



            }




        }

       catch (Exception ex)
        {
            Response.Write("Error: " + ex.Message.ToString());
        }
    }

Aspx code:

 <div class="form-group col-sm-1">
   <asp:TextBox ID="DateTxt" placeholder="Date" CssClass="form-control" runat="server" 
                ReadOnly="True">
   </asp:TextBox>

Make ReadOnly= "False"

The contents of the TextBox control cannot be changed if ReadOnly="True".And that's why DateTxt text values remains empty("") and it is throwing an Error: String was not recognized as a valid DateTime.

由于您的文本仅包含日期部分,因此请按如下所示更改代码,

DateTime dt = DateTime.ParseExact(DateTxt.Text, "MM/dd/yyyy",CultureInfo.InvariantCulture);

I've changed the code a little bit. Please check.

DateTime dt = DateTime.ParseExact(DateTxt.Text.Date, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM