简体   繁体   English

字符串未被识别为有效日期时间

[英]String was not recognized as Valid Datetime

I have 2 textboxes where I have to add the Joining Date and Leaving Date . 我有2个文本框,必须在其中添加Joining DateLeaving Date

Now When I add the joining date and leave the Leaving date blank and submit the form I get error as 现在,当我加入加入日期和离开的Leaving date空白,并提交我得到错误的形式

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. 最好的选择是为文本框使用日期验证器,如果输入的日期格式错误,则可以显示验证错误而不是RTE。

here is the question for validation: 这是验证的问题:

Date validation for a textbox 文本框的日期验证

here is the available date format from MSDN: 这是MSDN可用的日期格式:

https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx https://msdn.microsoft.com/zh-CN/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 : 您正在尝试转换为null的内容,就像您对编译器说的那样:

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) 使用DateTimePicker(例如jquery ui datetimepicker)
  3. use this code instead of that at the end of that line 使用此代码,而不是在该行的末尾

    String.IsNullOrEmpty(txtdol.Text) ? String.IsNullOrEmpty(txtdol.Text)吗? DateTime.Now : Convert.ToDateTime(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 . 如果txtdol为null或为空,则返回当前datetime,否则将txtdol转换为datetime并返回。

Good way to input date to Textbox by user is using : 1- MaskedTextBox or 2- DateTimePicker. 用户将日期输入到文本框的好方法是使用:1- MaskedTextBox或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 发生此错误是由于在文本框中输入了无效的日期格式(空或错误的格式)来解决此问题,请按如下所示修改代码,请使用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..!! 而且有效.. !!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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