本文介绍了在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
事件
EditYou can subscribe to CellFormatting
event like this
dataGridView1.CellFormatting += dataGridView1_CellFormatting;
希望对你有帮助
这篇关于在datagridview中显示是/否而不是真/假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!