簡體   English   中英

字符串未被識別為有效日期時間

[英]String was not recognized as Valid Datetime

我有2個文本框,必須在其中添加Joining DateLeaving Date

現在,當我加入加入日期和離開的Leaving date空白,並提交我得到錯誤的形式

字符串未被識別為有效日期時間

這是我的代碼

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

我不知道為什么這給錯誤。 請幫忙

更新:

文字框代碼:-

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

確保在文本框中以有效格式輸入日期。 最好的選擇是為文本框使用日期驗證器,如果輸入的日期格式錯誤,則可以顯示驗證錯誤而不是RTE。

這是驗證的問題:

文本框的日期驗證

這是MSDN可用的日期格式:

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

當然,您會因此而出錯。 錯誤發生在

Convert.ToDateTime(txtdol.Text);

您正在嘗試轉換為null的內容,就像您對編譯器說的那樣:

Convert.ToDateTime("");

它是空字符串,不能轉換。

您可以考慮以下一些選擇:

  1. 檢查文本框是否為空並且提供的日期是否有效(客戶端或服務器端)
  2. 使用DateTimePicker(例如jquery ui datetimepicker)
  3. 使用此代碼,而不是在該行的末尾

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

如果txtdol為null或為空,則返回當前datetime,否則將txtdol轉換為datetime並返回。

用戶將日期輸入到文本框的好方法是使用:1- MaskedTextBox或2- DateTimePicker。 或者,如果要使用文本框,也可以使用此代碼檢查空值。

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

對於驗證文本框,請檢查此功能:

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;
        }

發生此錯誤是由於在文本框中輸入了無效的日期格式(空或錯誤的格式)來解決此問題,請按如下所示修改代碼,請使用DateTime.ParsExact

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

第二個參數也可以更改為格式數組。

根據需要更改代碼

收到很多錯誤之后,像這樣

 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);
                        }

而且有效.. !!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM