DataGridView comboBoxColumn dateTime format

2019-08-14 23:54发布

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:

enter image description here

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条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-15 00:26

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.

查看更多
登录 后发表回答