简体   繁体   中英

String was not recognized as Valid Datetime

I have 2 textboxes where I have to add the Joining Date and Leaving Date .

Now When I add the joining date and leave the Leaving date blank and submit the form I get error as

String was not recognized as Valid Datetime

Here is my code for

cmd1.Parameters.Add("@leaving_date", SqlDbType.DateTime).Value = Convert.ToDateTime(txtdol.Text);

I dont know why this is giving error. Please help

UPDATE:

Textbox code:-

 <asp:TextBox ID="txtdol" CssClass="form-control" runat="server" ValidationGroup="AddNew" Enabled="true"></asp:TextBox>

Ensure you enter date in valid format in the textbox. best option is to use a date validator for the textbox and if the date formate entered is wrong you can display validation error rather than RTE.

here is the question for validation:

Date validation for a textbox

here is the available date format from MSDN:

https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

of course you get error for that . the error happening in

Convert.ToDateTime(txtdol.Text);

you are trying to convert something that is null , its like you say to compiler to compile this :

Convert.ToDateTime("");

it's emptry string and cannot be converted .

here are some options that you can consider of :

  1. Check if the textbox is not empty and the provided date is valid (client or server side)
  2. use DateTimePicker (like jquery ui datetimepicker)
  3. use this code instead of that at the end of that line

    String.IsNullOrEmpty(txtdol.Text) ? DateTime.Now : Convert.ToDateTime(txtdol.Text)

if txtdol is null or empty it return the current datetime otherwise it convert the txtdol to datetime and return it .

Good way to input date to Textbox by user is using : 1- MaskedTextBox or 2- DateTimePicker. Or if you want using textbox, you can use this code also to check empty values.

 DateTime? nullDateTime = null;
        cmd1.Parameters.Add("@leaving_date", SqlDbType.DateTime).Value = string.IsNullOrEmpty(txtdol.Text.Trim()) ? nullDateTime : Convert.ToDateTime(txtdol.Text.Trim())

and for validation textbox check this function:

private bool validateDate(TextBox arg1)
        {
            DateTime dt;
            bool valid1 = DateTime.TryParseExact(arg1.Text.Trim(), "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out dt);
            if (!string.IsNullOrEmpty(arg1.Text.Trim()) )
            {
                MessageBox.Show("Format Date is wrong! Currect format is(dd/MM/yyyy)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                arg1.Focus();
                return false;
            }
            return true;
        }

This error occures due to Invalid date format (empty or wrong format) enterd in textbox to fix the issue modify the code as below , use DateTime.ParsExact

cmd1.Parameters.Add("@leaving_date", SqlDbType.DateTime).Value = DateTime.ParsExact(txtdol.Text,"dd/MM/yyyy",System.Globalization.DateTimeStyles.AllowInnerWhite);

the second paramater can be changed to an array of format also.

Change the code as per your need

After getting so much errors, Did like this

 if (txtdol.Text == null || txtdol.Text == string.Empty)
                        {
                            cmd.Parameters.Add("@leaving_date", SqlDbType.DateTime).Value = DBNull.Value;
                        }
                        else
                        {
                            cmd.Parameters.Add("@leaving_date", SqlDbType.DateTime).Value = Convert.ToDateTime(txtdol.Text);
                        }

And it worked..!!

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