在 datagridview 中显示是/否而不是真/假 [英] show Yes/NO instead True/False in 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.处理 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
事件使其工作
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;
}
}
编辑您可以像这样订阅 CellFormatting
事件
Edit
You can subscribe to CellFormatting
event like this
dataGridView1.CellFormatting += dataGridView1_CellFormatting;
希望能帮到你
这篇关于在 datagridview 中显示是/否而不是真/假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!