ASP.Net Error: String was not recognized as a valid DateTime while inserting to Database

Last Reply on Apr 20, 2018 01:14 AM By nagaraju60

Posted on Apr 18, 2018 01:00 PM

The DateAndTime field in the sql table looks like this format: 4/19/2018 6:45:00 PM

In the index.aspx page, we would like it display the long date format and separate the time.

<asp:TemplateField HeaderText="Date & Time" HeaderStyle-HorizontalAlign="Center" SortExpression="DateAndTime">
    <itemtemplate>
        <%--<asp:Label ID="DateAndTime" runat="server" Text='<%#Eval("DateAndTime")%>'></asp:Label>--%>
        <asp:Label ID="DateAndTime" runat="server" Text='<%#Eval("DateAndTime", "{0:D}" + "<br />" + "{0:t}")%>'></asp:Label>
    </itemtemplate>
</asp:TemplateField>

I've the insert into the DB code looks like:

Dim lblDateAndTime= TryCast(row.FindControl("DateAndTime"), Label).Text
Dim dteParam As SqlParameter = sqlCmd.Parameters.Add("@DateAndTime", Data.SqlDbType.DateTime)
DateAndTimeParam.Value = lblDateAndTime

It gave me error " String was not recognized as a valid DateTime.

output displays just fine. I've trouble inserting dateandtime back into the db.

Can you you help how to insert the longdate/time formate into the DB?

You are viewing reply posted by: nagaraju60 on Apr 20, 2018 01:14 AM.
Posted on Apr 20, 2018 01:14 AM

Please refer below 

<asp:TemplateField HeaderText="Date & Time" HeaderStyle-HorizontalAlign="Center" SortExpression="DateAndTime">
    <itemtemplate>
       
        <asp:Label ID="DateAndTime" runat="server" Text='<%#Eval("DateAndTime",  "{0:dd/MM/yyyy hh:mm:ss}")%>'></asp:Label>
    </itemtemplate>
</asp:TemplateField>

 

Dim lblDateAndTime= TryCast(row.FindControl("DateAndTime"), Label).Text
Dim oDate As DateTime = DateTime.ParseExact(lblDateAndTime, "dd/MM/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

Dim dteParam As SqlParameter = sqlCmd.Parameters.Add("@DateAndTime", Data.SqlDbType.DateTime)
DateAndTimeParam.Value = oDate