show Yes/NO instead True/False in datagridview

后端 未结 5 535
余生分开走
余生分开走 2020-11-30 11:58

There is datagridview in a form that shows content of table of database, one column of table type is boolean, so in datagridview shows true/false, but i want to customize i

5条回答
  •  爱一瞬间的悲伤
    2020-11-30 12:34

    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

提交回复
热议问题