5
votes

I have a databound datagridview. In it I have a column that has NULL values and 1-12. How can I at runtime make the datagridview turn the 1 into January and display it in the cell? And the NULL into another pre-defined string?

I tried looking at the cell format, changed it to custom, then put in "MMM" but it did not work and displayed "MMM" in the actual cell.

Please help.

EDIT: Its winforms c#4.0, the field is bound to Int field from an entity in EF. And no need for culture sensitive, english is fine.

EDIT: I tried {0:MMM} it didnt work, just displayed {X:MMM} in cell where X is int.

Some screenshots:

format

result

2
Do you need this to be multilingual/culture sensitive? Plus is this currently bound to an 'int?' type?ChrisBD
Is this win forms? or ASP.NET?atoMerz

2 Answers

4
votes

If WinForms try this:

Use Column.DefaultCellStyle.Format property or set it in designer.

This post should clarify any doubt:

Customize format of DateTime string in WPF and WinForm data binding


PROBLEM: string formatting masks will only work with DateTime values. You have int and in this case I think you'll have to write a converter function...

Check this:

DataGridView.CellFormatting Event

1
votes

The simplest way of going about this is to create a separate property for databinding, such as DisplayMonth which contains the logic you want, then bind the cell to that property instead. Are you using EF-generated classes? If so, you can add this property to a partial class to extend the one generated by EF.

It would look something like:

public string DisplayMonth
{
  get { return ConvertToString(this.Date); //TODO: create ConvertToString method }
  set { return this.Date = ConvertFromString() //TODO: create ConvertFromString method ; }
}

As mentioned already, you can also use the CellFormatting event, however you'll need to re-implement it everywhere this object is used in a grid.