【问题标题】:DataGridView comboBoxColumn dateTime formatDataGridView comboBoxColumn 日期时间格式
【发布时间】:2014-01-01 16:58:51
【问题描述】:

Winform,带有组合框列的dataGridview。列数据源指向 Sql 表“dateTime”字段格式。每行包含一个数据,如 01/01/2014、01/02/2014 等。我正在尝试将 dataGridView 中的组合框单元格格式化为仅显示月/年。

我直接在设计器中尝试了自定义格式:

并附上代码:

dataGridView1.Columns["Periodo"].DefaultCellStyle.Format = ("{0:M/yyyy}");

像这样

dataGridView1.Columns["Periodo"].DefaultCellStyle.Format = "M/yyyy";

以及许多其他方面。我做错了,组合框一直显示 01/01/2014 类型格式。如何格式化此类列以获取“2014 年 1 月”、“2014 年 2 月”等?

【问题讨论】:

  • "MMM yyyy" 怎么样?
  • @SonerGönül。不,仍然没有改变任何东西,我试过这个:dataGridView1.Columns["Periodo"].DefaultCellStyle.Format = "MMM yyyy";

标签: c# datagridview string-formatting


【解决方案1】:

问题不在于您尝试的格式("M/yyyy" 很好),Format 属性也不起作用。问题是你所做的会影响单元格的内容,而不是组合框的内容。

避免DataGridViewComboBoxColumn/DataGridViewComboBoxCell 出现问题的最佳方法是处理组合框的项目,而不是单元格本身。示例代码:

DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.Name = "DateCol";
List<DateTime> dates = new List<DateTime>() { DateTime.Now.AddMonths(-1), DateTime.Now, DateTime.Now.AddMonths(1) };
//Dates = Dates.OrderBy(x => x).ToList();
List<string> colSource = dates.Select(x => x.ToString("M/yyyy")).ToList(); 
col.DataSource = colSource;

dataGridView1.Columns.Add(col);

在这段代码中,我正在处理日期列表(并最终对其进行排序或执行任何其他必需的操作);但随后我创建了一个(格式正确的)字符串列表作为组合框源。

【讨论】:

  • 非常感谢您的解决方案和解释。阅读您的答案后,我明白了。它工作得很好,我只是将格式更改为“MMM/yyyy”以获得我想要的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 2013-04-23
相关资源
最近更新 更多