将布尔值显示为“是”或“否”

本文关键字:布尔值 显示 | 更新日期: 2023-09-27 17:58:51

我正在查询数据库,并将值分配给一个对象,我将该对象序列化并显示在报告中。

问题是布尔变量在报告中显示为true或false。如何将值显示为"是"或"否"。

这是我的班级

public class ProductReportView
{
    public int Count { get; set; }
    public string ProductCode { get; set; }
    public string ProductTitle { get; set; }
    public string Producer { get; set; }
    public bool VideoOnDemand { get; set; }
    public bool PreviewScreen { get; set; }
    public bool QualityCheck { get; set; }
    public bool Archive { get; set; }
}

这就是我分配值的方式

OleDbDataReader dbreader = cmd.ExecuteReader();
while (dbreader.Read())
{
     Console.WriteLine("Record " + totalCount++);
     ProductReportView rep = new ProductReportView();
     rep.Count = ++totalCount;
     rep.ProductCode = (string)dbreader["CODE"];
     rep.ProductTitle = (string)dbreader["TITLE"];
     rep.Producer = (string)dbreader["PRODUCER"];
     rep.VideoOnDemand = (bool)dbreader["VideoOnDemand"];
     rep.PreviewScreen = (bool)dbreader["PreviewLibraryChecked"];
     rep.QualityCheck = (bool)dbreader["QualityCheck"];
     rep.Archive = (bool)dbreader["Archive"];
     lst.Add(rep);
}

这些值基于选中和未选中的复选框(VideoOnDemand、PreviewScreen QualityCheck、Archive)

将布尔值显示为“是”或“否”

你没有说你是如何"报告"的。。。

这有帮助吗?

   Control.Text = rep.VideoOnDemand ? "Yes" : "No";

在对象中存储值的过程中进行更改确实是个坏主意。所以在网格中的C#级别执行

Control.Text = rep.VideoOnDemand ? "Yes" : "No";

您也可以在Sql查询中执行此操作。

例如。

选择

案例VideoOnDemand当1表示"是"否则为"否"以"VideoOnDemand"结束

来自tblxyz

我的方法有4个简单的属性,提供了可重用性和清理代码:

public class ProductReportView
{
    public int Count { get; set; }
    public string ProductCode { get; set; }
    public string ProductTitle { get; set; }
    public string Producer { get; set; }
    public bool VideoOnDemand { get; set; }
    public bool PreviewScreen { get; set; }
    public bool QualityCheck { get; set; }
    public bool Archive { get; set; }
    private string toYesNo(bool b)
    {
        return b ? "Yes" : "No";
    }
    public string VideoOnDemandString
    {
        get { return this.toYesNo(this.VideoOnDemand); }
    }
    public string PreviewScreenString
    {
        get { return this.toYesNo(this.PreviewScreen); }
    }
    public string QualityCheckString
    {
        get { return this.toYesNo(this.QualityCheck); }
    }
    public string ArchiveString
    {
        get { return this.toYesNo(this.Archive); }
    }
}

此代码可以在所有应用程序中重复使用,而无需重复"是"、"否"、"是"answers"否"等。

最后建议:布尔应该存储在布尔属性中,字符串应该存储在字符串属性中。

不要持久化转换为字符串的布尔值:没有任何意义。

在对象中存储值时使用三元运算符

rep.VideoOnDemand = (bool)dbreader["VideoOnDemand"] ? "Yes" : "No";  

并将VideoOnDemand作为string

public string VideoOnDemand { get; set; }

对需要YES/NO 的其余变量使用相同的方法