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

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

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

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

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

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

希望这可以帮助

  void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { var grid = (DataGridView)sender; if (grid.Columns[e.ColumnIndex].Name == "IsActive") { e.Value = (bool)e.Value ? "True_Text_Replace" : "False_Text_Replace"; e.FormattingApplied = true; } } 

如果你只想展示,那怎么样。 这很容易想到。

 private void Form1_Load(object sender, EventArgs e) { List list = new List(); list.Add(new Person(20, true)); list.Add(new Person(25, false)); list.Add(new Person(30, true)); dgv.DataSource = list; //Hide checkbox column dgv.Columns["IsProgrammer"].Visible = false; //Add represent text column DataGridViewTextBoxColumn textColumn = new DataGridViewTextBoxColumn(); textColumn.Name = "Yes / No"; dgv.Columns.Add(textColumn); //true/false -> yes/no foreach (var row in dgv.Rows.Cast()) row.Cells["Yes / No"].Value = (bool)row.Cells["IsProgrammer"].Value ? "Yes" : "No"; } private class Person { public int Age { get; set; } public bool IsProgrammer { get; set; } public Person(int i, bool b) { Age = i; IsProgrammer = b; } }