Using a custom formatter in a DataGridView

人走茶凉 提交于 2019-11-28 11:37:17

You can indeed implement a custom ICustomFormatter, but due to some retardedness on the part of the DataGridView, you need to actually tell it how to apply your formatter.

First set column.DefaultCellStyle.FormatProvider to an instance of your custom formatting class. Then, handle the CellFormatting event:

void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
    if (e.CellStyle.FormatProvider is ICustomFormatter) {
        e.Value = (e.CellStyle.FormatProvider.GetFormat(typeof(ICustomFormatter)) as ICustomFormatter).Format(e.CellStyle.Format, e.Value, e.CellStyle.FormatProvider);
        e.FormattingApplied = true;
    }
}

The formatter class would look something like this:

public class MyEnumFormatter : IFormatProvider, ICustomFormatter {

    public object GetFormat(Type formatType) {
        if (formatType == typeof(ICustomFormatter))
            return this;
        else
            return null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider) {
        return ((NameOfEnumType)Convert.ToInt32(arg)).ToString();
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!