Data Formatting in the Windows Forms DataGridView Control
Thecontrol provides automatic conversion between cell values and the data types that the parent columns display. Text box columns, for example, display string representations of date, time, number, and enumeration values, and convert user-entered string values to the types required by the data store.
Formatting with the DataGridViewCellStyle class
The DataGridView control provides basic data formatting of cell values through theclass. You can use the property to format date, time, number, and enumeration values for the current default culture using the format specifiers described in . You can also format these values for specific cultures using the property. The specified format is used both to display data and to parse data that the user enters in the specified format.
The DataGridViewCellStyle class provides additional formatting properties for wordwrap, text alignment, and the custom display of null database values. For more information, see.
Formatting with the CellFormatting Event
If the basic formatting does not meet your needs, you can provide custom data formatting in a handler for theevent. The passed to the handler has a property that initially contains the cell value. Normally, this value is automatically converted to the display type. To convert the value yourself, set the Value property to a value of the display type.
If a format string is in effect for the cell, it overrides your change of the Value property value unless you set theproperty to true.
The CellFormatting event is also useful when you want to set DataGridViewCellStyle properties for individual cells based on their values. For more information, see.
If the default parsing of user-specified values does not meet your needs, you can handle theevent of the DataGridView control to provide custom parsing.