显示datagridview的是/否,而不是真/假 [英] show Yes/NO instead True/False in datagridview

查看:204
本文介绍了显示datagridview的是/否,而不是真/假的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有是在的datagridview显示数据库表内容的形式,表类型的一列是布尔值,所以在显示的datagridview真/假,但我想自定义显示是/否。
你认为哪种方式?

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 it to show Yes/No. which way you suggest?

推荐答案

当涉及到自定义格式,两种可能的解决方案来在我的脑海。

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

1.Handle CellFormatting 事件和格式化你自己的。

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,使用自定义格式化

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

然后使用它像这样,和处理 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;
     }
 }

修改
您可以订阅 CellFormatting 事件像这样

dataGridView1.CellFormatting += dataGridView1_CellFormatting;

希望这有助于

这篇关于显示datagridview的是/否,而不是真/假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆