【问题标题】:C# - format DataGridView date into messageboxC# - 将 DataGridView 日期格式化为消息框
【发布时间】:2021-10-29 15:38:47
【问题描述】:

我有一个连接到 sql 数据库的 datagridview,一切正常。 我想在 MessageBox 上显示格式为“dd/MM/yyyy”的字段“日期”(数据库上的日期时间)。

我是这样的:

 MessageBox.Show(dataGridView1.CurrentRow.Cells[4].Value.ToString());

它显示:

我可以在代码中添加或编辑什么来删除小时数?

【问题讨论】:

    标签: c# database datagridview messagebox


    【解决方案1】:

    将正确的日期格式,即"dd/MM/yyyy" 作为参数传递给ToString()

    //As per your comment it seems type of ..Cells[4].Value is DateTime?
    string dateValue =  dataGridView1.CurrentRow.Cells[4].Value?.ToString("dd/MM/yyyy") ?? "No Date Found";
    MessageBox.Show(dateValue);
                                                
    

    使用正确的月份格式,

    mm - Prints minute (00 - 59)
    MM - Prints month (00 - 12)
    

    【讨论】:

    • 它返回错误:“ToString 方法没有重载需要 1 个参数”
    • dataGridView1.CurrentRow.Cells[4].ValueDateTime? 类型吗?如果是,那么如果dataGridView1.CurrentRow.Cells[4].Value 为空,您要打印什么?
    • @MMelo31 我更新了我的答案以支持DateTime? 数据类型
    【解决方案2】:

    已修复:

    string message = (dataGridView1.CurrentRow.Cells[4].Value.ToString());
    MessageBox.Show(message.Remove(10).ToString()
    

    这样做是删除字符串的最后一个字符,在这种情况下,字符是时间

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多