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
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.Use 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
}
}
}
}
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;
}
}
Edit
You can subscribe to CellFormatting
event like this
dataGridView1.CellFormatting += dataGridView1_CellFormatting;
Hope this helps
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With