This is a similar question to How to bind a custom Enum description to a DataGrid, but in my case I have multiple properties.
public enum ExpectationResult
{
[Description("-")]
NoExpectation,
[Description("Passed")]
Pass,
[Description("FAILED")]
Fail
}
public class TestResult
{
public string TestDescription { get; set; }
public ExpectationResult RequiredExpectationResult { get; set; }
public ExpectationResult NonRequiredExpectationResult { get; set; }
}
I'm binding a BindingList<TestResult> to a WinForms DataGridView (actually a DevExpress.XtraGrid.GridControl, but a generic solution would be more widely applicable). I want the descriptions to appear rather than the enum names. How can I accomplish this? (There are no constraints on the class/enum/attributes; I can change them at will.)
A TypeConverter
will usually do the job; here's some code that works for DataGridView
- just add in your code to read the descriptions (via reflection etc - I've just used a string prefix for now to show the custom code working).
Note you would probably want to override ConvertFrom
too. The converter can be specified at the type or the property level (in case you only want it to apply for some properties), and can also be applied at runtime if the enum isn't under your control.
using System.ComponentModel;
using System.Windows.Forms;
[TypeConverter(typeof(ExpectationResultConverter))]
public enum ExpectationResult
{
[Description("-")]
NoExpectation,
[Description("Passed")]
Pass,
[Description("FAILED")]
Fail
}
class ExpectationResultConverter : EnumConverter
{
public ExpectationResultConverter()
: base(
typeof(ExpectationResult))
{ }
public override object ConvertTo(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture, object value,
System.Type destinationType)
{
if (destinationType == typeof(string))
{
return "abc " + value.ToString(); // your code here
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
public class TestResult
{
public string TestDescription { get; set; }
public ExpectationResult RequiredExpectationResult { get; set; }
public ExpectationResult NonRequiredExpectationResult { get; set; }
static void Main()
{
BindingList<TestResult> list = new BindingList<TestResult>();
DataGridView grid = new DataGridView();
grid.DataSource = list;
Form form = new Form();
grid.Dock = DockStyle.Fill;
form.Controls.Add(grid);
Application.Run(form);
}
}
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