【问题标题】:DataGridView automatically charges TIME if value is a DATE (C# & SQL Server 2008)如果值为 DATE,DataGridView 会自动对 TIME 收费(C# & SQL Server 2008)
【发布时间】:2016-05-14 06:24:33
【问题描述】:

我是新来的,只是为了快乐而发展(如果我的英语不够好,请原谅我是墨西哥人)

我注意到,当从 DataGridView 检索日期值时,它会自动添加时间补码(默认情况下为上午 12:00:00) 这是一个例子

事实 #1

我将值存储在 SQL Server 2008 表中,将此行添加到我的查询中

dateTimePicker1.Value.ToString("yyyy-MM-dd") 

(这里只存储日期,SQL列值为Date类型)

事实 #2

我将我的表计入 DataGridView(在 Date 字段中它只显示一个日期)

事实 #3

我使用查询将 DataGridView 充电到数据集数据表中

    datasets.DataSet1 ds = new datasets.DataSet1();
    datasets.DataSet1.DataTable1 dt = new datasets.DataSet1.DataTable1();

    for (i = 0; i < DataGridView1.Rows.Count(); i++)
    {
        DataRow dRow = dt.NewRow();
        dRow["id"] = dataGridView1.Rows[i].Cells[0].Value.ToString();
        dRow["date"] = dataGridView1.Rows[i].Cells[1].Value.ToString();
        dt.Rows.Add( dRow );
    }

事实 #4

如果我在这一行设置断点

Row["date"] = dataGridView1.Rows[i].Cells[1].Value.ToString();

“值”属性显示(例如)

dataGridView1.Rows[i].Cells[1].Value = {13/05/2016 12:00:00 a.m.}

事实 #5 我检查了我的数据集,所有值都是 System.String - 类型 在 SQL Server 检查前 200 行时,它仅存储日期 2016-05-13,而不是任何时间

你们知道 DataGridView 是从哪里获取时间值的吗?当我在通知 (.rdlc) 中打开我的数据集和数据表时,它会显示日期和时间补码

【问题讨论】:

    标签: c# sql-server-2008 datagridview datatable dataset


    【解决方案1】:

    .Net 中没有 Sql Server 中的“日期”类型。在.Net 中只有DateTime Structure。要获得正确的映射数据类型,请阅读SQL Server Data Type Mappings

    所以在内部,在每个包含 Date 值的对象中,实际上都有一个 DateTime,其默认时间部分为 00:00:00.000

    请始终牢记,DateTime 值代表时间中的某个时刻。

    希望这对您有所帮助。

    【讨论】:

      【解决方案2】:

      如果您只想要 DateTimePicker 中的日期,那么您可以这样做:

      dateTimePicker1.Value.ToShortDateString();
      

      这意味着您只需拨打ToShortDateString();
      更多信息可以查看this链接。

      【讨论】:

      • 当您使用 dateTimePicker 之类的时间处理程序时有效,但是当我尝试使用该代码行 dataGridView1.Rows[i].Cells[1].Value.ToShortDateString() 时它没有不认识它,我必须添加额外的参考吗?
      • 正如您在问题的“事实 #1”中提到的,您将值存储在 SQL Server 2008 表中,如“dateTimePicker1.Value.ToString("yyyy-MM-dd")”,现在将其更改为“dateTimePicker1.Value.ToShortDateString()”。然后在您不必将该值转换为 ToShortDateString() 之后,因为它会自动将日期作为输入。
      【解决方案3】:

      您可以使用 DefaultCellStyle 属性格式化 DataGridView 列中的 DateTime。请参考以下示例。

      dataGrid.Columns[1].DefaultCellStyle.Format = "yyyy-MM-dd";
      

      现在从 DataGridView 单元格中获取日期值时,将 DateTime 转换为日期字符串。

      var date=Convert.ToDateTime(dataGridView1.Rows[i].Cells[1].Value).ToString("yyyy-MM-dd");
      

      我希望这能解决你的问题。

      【讨论】:

        猜你喜欢
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 2013-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多