0

当我的 formview 尝试插入具有字符串日期的记录需要进入 SQL Server 中的 datetime 列时,我遇到了强制转换异常。该字段使用Bind方法绑定到表列,是FormView的InsertItemTemplate的一部分。我不确定如何在插入期间将字符串转换为日期时间。我想也许使用插入命令来转换(日期时间,@PDate,101)?那没有解决问题。

请告诉我你的想法。我感谢任何帮助和建议。

*编辑 *

这是设置当前日期的代码

Protected Sub FormView1_DataBound(sender As Object, e As System.EventArgs) Handles FormView1.DataBound
    If FormView1.CurrentMode = FormViewMode.Insert Then
        Dim tb As New TextBox
        tb = FormView1.FindControl("textPDate")
        tb.Text = FormatDateTime(DateTime.Now, DateFormat.ShortDate).ToString
    End If
End Sub

这是文本框的标记

<asp:TextBox ID="textPDate" runat="server" Style="position:absolute; top: 140px; left:181px; width: 200px;" 
            Text='<%# Bind("PDate") %>'></asp:TextBox>

这是我在插入期间所做的其他一些计算

Protected Sub FormView1_ItemInserting(sender As Object, e As System.Web.UI.WebControls.FormViewInsertEventArgs) Handles FormView1.ItemInserting
    Dim paper As New DropDownList
    Dim cylinder As New DropDownList
    Dim blockcode As New TextBox

    paper = FormView1.FindControl("dropdownPaperItem")
    cylinder = FormView1.FindControl("dropdownCylinderNumber")
    blockcode = FormView1.FindControl("textBlockCode")
    Dim c As New Common
    blockcode.Text = c.CalcBlockCode(paper.Text, cylinder.Text)

End Sub

我想也许我可以在 ItemInserting 事件中将字符串转换为日期时间,但我不确定。

4

2 回答 2

1

如果您知道dd/MM/yyyy要支持的确切格式(在此示例中),请使用TryParseExact,如下所示:

Dim dt As DateTime

DateTime.TryParseExact(textBox.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, dt)

然后您可以在调用后检查是否dt为空TryParseExact(),如下所示:

If Not dt Is Nothing
    ' Text box text is a valid date, pass the date to the database
End If

您可以在表单视图的项目插入事件中使用此逻辑,如下所示:

Sub FormView1_ItemInserting(ByVal sender As Object, ByVal e As FormViewInsertEventArgs)
    Dim dt As DateTime

    DateTime.TryParseExact(textBox.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, dt)

    If dt Is Nothing
        ' Use the Cancel property to cancel the insert operation.
        e.Cancel = True
    End If
End Sub
于 2013-10-28T17:54:06.910 回答
1
DateTime dateTime;

DateTime.TryParseExact(textBox1.Text, 
                       "dd/MM/yyyy", //you can specify any desired format here
                       CultureInfo.InvariantCulture, 
                       DateTimeStyles.None, 
                       out dateTime);
于 2013-10-28T17:55:20.620 回答