2

如何在datagridview单元格中将用户值为12345678的字符串显示为:1234/56/78
我想我应该使用DataGridViewColumnDefaultCellStyle.Format属性,但我不知道合适的值是什么。
我使用的.NET Framework 2.0在DataGridViewColumn中格式化单元格

回答

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

,你可以这样设置格式的情况下

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

这篇对你的工作? – V4Vendetta 2011-05-03 06:43:42