在datagridview中显示Yes/NO而不是True/False

Mil*_*hiz 7 c# boolean datagridview

在显示数据库表的内容的表单中有datagridview,表格类型的一列是布尔值,因此在datagridview中显示true/false,但我想自定义它以显示是/否.你建议哪种方式?

Sri*_*vel 18

在自定义格式化方面,我想到了两种可能的解决方案.

1.处理CellFormatting事件并格式化您自己的事件.

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;
         }
     }
 }
Run Code Online (Sandbox Code Playgroud)

2.使用 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
                }
        }
    }
 }
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它,并处理CellFormatting事件以使其工作

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;
     }
 }
Run Code Online (Sandbox Code Playgroud)

编辑 您可以订阅CellFormatting此类活动

dataGridView1.CellFormatting += dataGridView1_CellFormatting;
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助

  • @MiladSobhkhiz不确定您的意思,您必须订阅“ CellFormatting”事件,该事件将在每次向网格显示值之前发生。检查我的编辑。 (2认同)