【问题标题】:Formatting Cells in DataGridViewColumn格式化 DataGridViewColumn 中的单元格
【发布时间】:2011-08-16 02:23:38
【问题描述】:
如何在 datagridview 单元格中向用户显示值为:12345678 的字符串:1234/56/78。
我想我应该使用DataGridViewColumn的DefaultCellStyle.Format属性,但是我不知道合适的值是什么。
我正在使用 .NET Framework 2.0
【问题讨论】:
标签:
winforms
datagridview
string-formatting
datagridviewcolumn
【解决方案1】:
您可以为您的案例设置这样的格式
foreach (DataGridViewRow var in dataGridView1.Rows)
{
(var.Cells[7] as DataGridViewTextBoxCell).Style.Format = "0000/00/00";
}
【解决方案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());
}
}
}