【问题标题】:How to insert value of type DateTime [duplicate]如何插入日期时间类型的值[重复]
【发布时间】:2020-11-30 03:53:17
【问题描述】:

在我的表中,我有两列StartedDateEndDate,它们都定义为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.ToDateTimeDatetime.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


【解决方案1】:

DateTime.Parse方法:

SqlDataSource1.InsertParameters["StartedDate"].DefaultValue = DateTime.Parse(((TextBox)GridView1.FooterRow.FindControl("startDate")).Text);

【讨论】:

  • 我确实尝试过,如问题帖子中所述。我收到以下错误:错误 CS0029 无法将类型“System.DateTime”隐式转换为“字符串”
猜你喜欢
  • 2014-02-20
  • 2018-10-27
  • 2012-11-10
  • 2016-08-20
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
相关资源
最近更新 更多