show Yes/NO instead True/False in datagridview

When it comes to custom formatting, two possible solutions comes in my mind.

1.Handle CellFormatting event and format your own.

void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
     if (e.ColumnIndex == yourcolumnIndex)
     {
         if (e.Value is bool)
         {
             bool value = (bool)e.Value;
             e.Value = (value) ? "Yes" : "No";
             e.FormattingApplied = true;
         }
     }
 }

2.Use Custom Formatter

public class BoolFormatter : ICustomFormatter, IFormatProvider
{
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
        {
            return this;
        }
        return null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (arg == null)
        {
            return string.Empty;
        }

        bool value = (bool)arg;
        switch (format ?? string.Empty)
        {
             case "YesNo":
                {
                    return (value) ? "Yes" : "No";
                }
            case "OnOff":
                {
                    return (value) ? "On" : "Off";
                }
            default:
                {
                    return value.ToString();//true/false
                }
        }
    }
 }

Then use it like this, and handle CellFormatting event to make it work

dataGridView1.Columns[1].DefaultCellStyle.FormatProvider = new BoolFormatter();
dataGridView1.Columns[1].DefaultCellStyle.Format = "YesNo";

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

Edit
You can subscribe to CellFormatting event like this

dataGridView1.CellFormatting += dataGridView1_CellFormatting;

Hope this helps

Leave a Comment