DataGridView comboBoxColumn dateTime format

白昼怎懂夜的黑 提交于 2019-12-24 16:06:17

问题


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:

and with the code:

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

and like this

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

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..?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/20870936/datagridview-comboboxcolumn-datetime-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!