Форматирование ячеек в DataGridViewColumn - PullRequest
2 голосов
/ 30 апреля 2011

Как я могу отобразить строку со значением: 12345678 пользователю в ячейке просмотра данных как: 1234/56/78.
Я думаю, что я должен использовать свойство DefaultCellStyle.Format DataGridViewColumn, но я нене знаю, какое значение подходит.
Я использую .NET Framework 2.0

Ответы [ 2 ]

3 голосов
/ 02 мая 2011

вы можете установить такой формат для вашего случая

foreach (DataGridViewRow var in dataGridView1.Rows)
{
    (var.Cells[7] as DataGridViewTextBoxCell).Style.Format = "0000/00/00";
}
2 голосов
/ 01 мая 2011
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());
      }
   }
}
...