第一步:继承ICustomFormatter, IFormatProvider接口,并实现
实例代码:
ICustomFormatter, IFormatProvider接口实现类
public class KmFormatProvider : ICustomFormatter, IFormatProvider
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
{
return this;
}
else return null;
throw new NotImplementedException();
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
//兜底处理
if (format == null)
{
if (arg is IFormattable)
return ((IFormattable)arg).ToString(format, formatProvider);
return arg.ToString();
}
else
{
if (format == "KM")
{
//此处编写自己需要的字符串格式转化方法
return BSConvert.DoubleToKmString(BSConvert.ToDouble(arg));
}
else //兜底处理
{
if (arg is IFormattable)
return ((IFormattable)arg).ToString(format, formatProvider);
return arg.ToString();
}
}
}
}
第二步:界面初始化Load事件中获取DataGridView表头列DataGridViewTextBoxColumn,设置并帮定FormatProvider接口
绑定自定格式接口
private void InsSubstructureForm_Load(object sender, EventArgs e)
{
//桩号格式化显示
DataGridViewColumn dataGridViewColumn = this.DGV_InsSubstructureList.Columns["mileagemark"];
DataGridViewTextBoxColumn gridViewTextBoxColumn = dataGridViewColumn as DataGridViewTextBoxColumn;
if (!gridViewTextBoxColumn.HasDefaultCellStyle)
gridViewTextBoxColumn.DefaultCellStyle = new System.Windows.Forms.DataGridViewCellStyle();
gridViewTextBoxColumn.DefaultCellStyle.FormatProvider = new KmFormatProvider();
gridViewTextBoxColumn.DefaultCellStyle.Format = "KM";
}
第三步:添加并处理DataGridView的CellFormatting事件
处理CellFormatting事件
private void DGV_InsSubstructureList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
var formatter = e.CellStyle.FormatProvider as ICustomFormatter;
if (formatter != null)
{
e.Value = formatter.Format(e.CellStyle.Format, e.Value, e.CellStyle.FormatProvider);
e.FormattingApplied = true;
}
}