DataGridView comboBoxColumn dateTime格式 [英] DataGridView comboBoxColumn dateTime format
问题描述
Winform,带有comboBox列的dataGridview。列数据源指向Sql表 dateTime字段格式。每行都包含2014年1月1日,2014年2月1日等数据。我正在尝试格式化dataGridView中的comboBox单元格以仅显示月份/年份。
Winform, dataGridview with a comboBox column. The column datasource is pointing to an Sql table "dateTime" field format. Each row contains a data like 01/01/2014, 01/02/2014, etc.. I am trying to format the comboBox cell in dataGridView to show only month/Year.
我直接在设计器中尝试了自定义格式:
I tried directly in the designer with a custom format:
,并输入以下代码:
dataGridView1.Columns["Periodo"].DefaultCellStyle.Format = ("{0:M/yyyy}");
像这样
dataGridView1.Columns["Periodo"].DefaultCellStyle.Format = "M/yyyy";
以及其他许多方式。我无法正确理解,comboBox继续显示2014年1月1日类型格式。如何格式化此类列以获取 2014年1月, 2014年2月等??
and in many other ways. I cannot get it right, the comboBox keeps showing 01/01/2014 type format. How can I format such column to get "January 2014", "February 2014", etc..?
推荐答案
问题是 Format
属性不能正常工作( M / yyyy
可以)。问题是您所做的操作会影响单元格的内容,而不是组合框的内容。
The problem is not in the format you tried ("M/yyyy"
is fine) neither in the Format
property not working. The problem is that what you did affects the cell contents, not the combobox contents.
避免使用 DataGridViewComboBoxColumn $ c出现问题的最佳方法$ c> /
DataGridViewComboBoxCell
正在处理组合框的项目,而不是单元格本身。示例代码:
The best way to avoid problems with DataGridViewComboBoxColumn
/DataGridViewComboBoxCell
is dealing with the items of the combobox, rather with the cell itself. Sample code:
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);
在此代码中,我正在处理日期列表(并最终对其进行排序或执行任何其他需要采取的措施);但是随后我创建了一个(格式正确的)字符串列表作为组合框源。
In this code, I am dealing with the list of dates (and, eventually, ordering it or performing any other required action); but then I create a list of (properly-formatted) strings to be the combobox source.
这篇关于DataGridView comboBoxColumn dateTime格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!