【发布时间】:2020-11-30 03:53:17
【问题描述】:
在我的表中,我有两列StartedDate 和EndDate,它们都定义为Date 数据类型。
我正在尝试通过日期类型的文本字段为这两列插入值,如下所示:
<asp:Textbox type="date" ID="startDate" runat="server"></asp:Textbox>
<asp:Textbox type="date" ID="endDate" runat="server"></asp:Textbox>
我正在尝试从这些文本框中检索值并将它们插入到我的数据库中。
这是我的插入代码:
// Insert a new row in the Task table
SqlDataSource1.InsertParameters["Task"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtTask")).Text;
SqlDataSource1.InsertParameters["StartedDate"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("startDate")).Text;
SqlDataSource1.InsertParameters["EndDate"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("endDate")).Text;
SqlDataSource1.InsertParameters["Done"].DefaultValue = ((CheckBox)GridView1.FooterRow.FindControl("DoneCbx")).Checked == true ? "true" : "false";
SqlDataSource1.InsertParameters["Priority"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("PriorityTxt")).Text;
// Method to execute the insert
SqlDataSource1.Insert();
Insert 工作得很好,除了日期字段,因为从文本框中检索到的值需要转换为 DateTime。
我尝试了Convert.ToDateTime 和Datetime.Parse 方法,但两次都出现以下错误:
无法将类型“System.DateTime”隐式转换为“字符串”
【问题讨论】:
-
请向我们展示表格的
CREATE TABLE脚本。 -
@mjwills CREATE TABLE [dbo].[TaskTable] ([ToDoId] INT IDENTITY (1, 1) NOT NULL, [Task] VARCHAR (250) NOT NULL, [StartedDate] DATE NULL, [ EndDate] DATE NULL, [Done] BIT NULL, [Priority] INT NOT NULL, PRIMARY KEY CLUSTERED ([ToDoId] ASC) );
-
使用代码在您的问题中 - a) 它编译成功了吗? b) 它运行了吗? c) 究竟有什么不适合它的?
-
@mjwills 如果我不添加开始日期和结束日期的值(它们可以是 null ),那么它工作正常。但我无法插入日期值,如果我这样做,它会引发异常:system.formatexception 字符串在第 32 行未被识别为有效日期时间,即 SqlDataSource1.Insert()
-
按照下面的答案做 - 但在结果上调用
ToString,就像在副本中一样。需要明确的是 - 你应该避免使用SqlDataSource,因为它是垃圾(垃圾的原因之一是你刚刚遇到的问题)。
标签: c# asp.net visual-studio