简体   繁体   中英

My error is string was not recognized as a valid DateTime

I'm having this error if i leave the date blank when I click save button.

Front Code

Date

<asp:TextBox ID="txtDate" runat="server" CssClass="text_300" MaxLength="200"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate" Format="dd/MM/yyyy"></asp:CalendarExtender>
<asp:MaskedEditExtender TargetControlID="txtDateFrom" Mask="99/99/9999"
    MessageValidatorTip="true" OnFocusCssClass="MaskEditFocus" OnInvalidCssClass="MaskEditError"
    MaskType="Date"
    ErrorTooltipEnabled="True" runat="server" ID="mskD" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
    ErrorMessage="*" ControlToValidate="txtDate" SetFocusOnError="True"></asp:RequiredFieldValidator>

Back Code

string result = _bllstaff.addInfo(Convert.ToDateTime(this.txtDateFrom.Text == "" 
    ? 0.ToString() : this.txtDateFrom.Text), _pUser.IDUSER, 
    DateTime.Now, dtCurrentTable);

This error occurs if I leave it blank after click save button. Maybe you guys have idea or suggestion for me. Thank you.

It's hard to understand exactly what issue you are having. Maybe revising your question, posting more code, and using a code block will help. EDIT: (I see the question has been updated)

I'll attempt a suggestion however; My advice would be to use the DateTime.Parse method, or even better DateTime.TryParse and make the code easier to follow:

//...
DateTime date = DateTime.MinValue;
DateTime.TryParse(this.txtDateFrom.Text, out date);
string result = _bllstaff.addInfo(date, _pUser.IDUSER, DateTime.Now, dtCurrentTable);
//...

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