在DataGridViewColumn中格式化单元格

时间:2011-04-30 14:57:02

标签: winforms datagridview string-formatting datagridviewcolumn

如何在datagridview单元格中向用户显示值为12345678的字符串:1234/56/78
我想我应该使用DefaultCellStyle.Format的{​​{1}}属性,但我不知道它的适当值是什么。
我正在使用.NET Framework 2.0

2 个答案:

答案 0 :(得分:3)

你可以为你的案例设置这样的格式

foreach (DataGridViewRow var in dataGridView1.Rows)
{
    (var.Cells[7] as DataGridViewTextBoxCell).Style.Format = "0000/00/00";
}

答案 1 :(得分:2)

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());
      }
   }
}