当我的formview尝试插入一个记录时,我得到一个强制转换异常,该记录的字符串日期需要进入SQL Server的datetime列。 该字段使用Bind方法绑定到表列,并且是FormView的InsertItemTemplate的一部分。 我不确定如何在插入过程中将字符串转换为日期时间。我想可能使用Insert Command转换(datetime,@ PAGE,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事件中将字符串转换为日期时间,但我不确定。
答案 0 :(得分: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
答案 1 :(得分:1)
DateTime dateTime;
DateTime.TryParseExact(textBox1.Text,
"dd/MM/yyyy", //you can specify any desired format here
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateTime);