Using custom formatting in a DataGridView

So maybe this is a bad design; I dont know. But tell me what I have DataTablewith a column that contains values int; these values ​​are actually intended to represent some type enumthat I have in my project.

What I would like to do is bind DataGridViewto this table, and the column will display the name enum, not the integer value "0" or "1" or something else.

One of the options that I considered was to do all the normalization: add a table in DataSetwith the names enumin it, typing the values enum, and my first table contains a link to this table.

But this is a enumspecific idea. I would like to know if I can generally write their own implementation IFormatProvider, and ICustomFormatterfor the type and use this formatter to control how the values are displayed in the column of the control DataGridView(or indeed in any administration, for that matter).

* This is how I suspect that this will be done, if what I ask is possible at all. I am not at all sure that I am using these interfaces.

+3
source share
1 answer

ICustomFormatter, - DataGridView , .

column.DefaultCellStyle.FormatProvider . CellFormatting:

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

formatter :

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

}
+9

Source: https://habr.com/ru/post/1761190/


All Articles