Search code examples
winformsdatagridviewstring-formattingdatagridviewcolumn

Formatting Cells in DataGridViewColumn


How can I display the string with value: 12345678 to the user in a datagridview cell as: 1234/56/78.
I think I should use the DefaultCellStyle.Format property of the DataGridViewColumn, But I don't know what the appropriate value is.
I'm using .NET Framework 2.0


Solution

  • using System;
    using System.Windows.Forms;
    
    namespace DGVFormatColumn
    {
       public class MyCell : DataGridViewTextBoxCell
       {
          protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter valueTypeConverter, System.ComponentModel.TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context)
          {
             String fullString = Value as String;
    
             // if we don't have an 8 character string, just call the base method with the values which were passed in
             if (fullString == null || fullString.Length != 8 || IsInEditMode)
                return base.GetFormattedValue(value, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context);
    
             // split the string into 3 parts
             String[] parts = new String[3];
             parts[0] = fullString.Substring(0, 4);
             parts[1] = fullString.Substring(4, 2);
             parts[2] = fullString.Substring(6, 2);
    
             // combine the parts with a "/" as separator
             String formattedValue = String.Join("/", parts);
    
             return formattedValue;
          }
       }
    
       class MyForm : Form
       {
          public MyForm()
          {
             // create a datagridview with 1 column and add it to the form
             DataGridView dgv = new DataGridView();
             DataGridViewColumn col = new DataGridViewColumn(new MyCell()); // use my custom cell as default cell template
             dgv.Columns.Add(col);
             this.Controls.Add(dgv);
          }
       }
    
       static class Program
       {
          static void Main()
          {
             Application.Run(new MyForm());
          }
       }
    }