【问题标题】:Error : No overload for method "ToString" takes 1 arguments错误:方法“ToString”没有重载需要 1 个参数
【发布时间】:2022-01-04 20:58:12
【问题描述】:

我想将所有 DataGridView 行插入数据库。 我遇到了这个错误

方法“ToString”没有重载需要 1 个参数。

 for (int i = 0; i < TimesDgv.Rows.Count - 1; i++)
 {
      OleDbCommand cmd = new OleDbCommand("Insert into TimesTBL(PeriodName,TimeFrom,TimeTo,Duration) values (@PeriodName,@TimeFrom,@TimeTo,@Duration)", con);
      cmd.Parameters.AddWithValue("PeriodName", TimesDgv.Rows[i].Cells[0].Value);
      cmd.Parameters.AddWithValue("TimeFrom", TimesDgv.Rows[i].Cells[1].Value.ToString("hh:mm"));
      cmd.Parameters.AddWithValue("TimeTo", TimesDgv.Rows[i].Cells[2].Value.ToString("hh:mm"));
      cmd.Parameters.AddWithValue("Duration", TimesDgv.Rows[i].Cells[3].Value);
      con.Open();
      cmd.ExecuteNonQuery();
      con.Close();
      cmd = null;
  }

enter image description here

【问题讨论】:

  • 我的问题通过Convert.ToDateTimeConvert.ToDateTime(TimesDgv.Rows[i].Cells[1].Value).ToString("hh:mm")解决了
  • 问题是DataGridViewCell.Value 属性被键入为object(想想看,一个单元格可以容纳任何东西,它必须是object 类型)docs.microsoft.com/en-us/dotnet/api/…。在您的特定情况下,该对象指的是 DateTime,但属性类型是对象。你不必转换它,你可以简单地转换它
  • 如何投射?
  • ((DateTime)(TimesDgv.Rows[i].Cells[2].Value)).ToString("Format")

标签: c# datetime ms-access


【解决方案1】:

您似乎认为TimesDgv.Rows[i].Cells[1].Value 是DateTime 或TimeSpan。但事实并非如此。就您的编译器而言,不是。

也许您打算将其解析或转换为一个?

【讨论】:

  • (TimesDgv.Rows[i].Cells[1].Value) 包含此值(2021 年 11 月 27 日上午 1:20)但我只想插入我的表时间(1:20 )。
  • 好吧,正如我所说,您需要先将其转换为 Parse 或将其转换为 DateTime。由于我们不知道TimesDgv.Rows[i].Cells[1].Value 是什么类型,因此任何人都可以为您提供尽可能多的帮助。也许你可以发一个minimal reproducible example?
猜你喜欢
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
相关资源
最近更新 更多