I need to make a format/mask in a cell that prevents the user from entering data that isn't relevant.
The column cell contains date values like "MM/YYYY"
without a day value.
I tried the following to make this definition but without success:
dataGridView1.Columns[0].DefaultCellStyle.Format = "##/####" // || dd/yyyy
Also, I tried to go to the properties of DataGridView
and define Format
from there.
The method you're using for formatting is a valid approach. There are a few issues that may be happening here. Please ensure:
DateTime
and not typestring
. Typestring
will not apply the format as expected. (See columns 1 and 2 in example below.)DataGridViewTextBoxCell.Style.Format
isn't being set to something different than your desired format. This would override the column formatting. (See column 3 in example below.)EXAMPLE
As you can see from the output:
Columns[0]
contains aDateTime
and correctly formats as"dd/yyyy"
.Columns[1]
contains astring
and cannot be reformatted to"dd/yyyy"
.Columns[2]
contains a formattedstring
and cannot be reformatted to"dd/yyyy"
.Columns[3]
contains aDateTime
and formatting is overridden by the cell format"MM/yyyy"
.To correct these issues, just set your cell value using the
DateTime
object and not anystring
representation.In the case where you are getting this data from some outside source and it's already of type
string
, you canParse
it, but note that the missing portions of theDateTime
object will be defaulted and there's really nothing you can do about that without having the original full data:Validation
If validating user input (and losing formatting on edits) is your main concern, consider the following method for validation to cancel an invalid edit:
Coupled with this answer for reapplying your format using the
DataGridView.CellFormatting
event handler. (Note that this also negates the need to ensure your data types are notstring
, but is more costly due to the event being triggered often.)