New to Telerik UI for WinForms? Start a free 30-day trial
Bind GridViewComboBoxColumn to Enum Type Property
Updated over 6 months ago
Environment
| Product Version | Product | Author |
|---|---|---|
| 2021.3.914 | RadGridView for WinForms | Dinko Krastev |
Description
A common requirement is to show enum values in GridViewComboBoxColumn. To do that we can create a custom wrapper class that will return a collection holding all values of an Enum. Then we can create a custom Enum type object.
Generic Enum Wrapper Class
C#
public class EnumWrapper<T>
{
public int ID
{
get;
set;
}
public string Name
{
get { return Enum.GetName(typeof(T), ID); }
set { ID = (int)Enum.Parse(typeof(T), value); }
}
public EnumWrapper(T value)
{
ID = (int)Enum.Parse(typeof(T), value.ToString());
}
public static List<EnumWrapper<T>> EnumToList<T>()
{
Type enumType = typeof(T);
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T must be of type System.Enum");
Array enumValArray = Enum.GetValues(enumType);
List<EnumWrapper<T>> enumValList = new List<EnumWrapper<T>>();
foreach (int val in enumValArray)
{
enumValList.Add(new EnumWrapper<T>((T)Enum.Parse(enumType, val.ToString())));
}
return enumValList;
}
}
enum EnumResultType
{
A,B,C
}
What's left is to create some dummy data and set our GridViewComboBoxColumn to show enum values of custom Enum type.
Bind GridViewComboBoxColumn To Enum Type
C#
DataTable table = new DataTable();
table.Columns.Add("Value", typeof(int));
table.Rows.Add((int)EnumResultType.A);
table.Rows.Add((int)EnumResultType.B);
table.Rows.Add((int)EnumResultType.C);
GridViewComboBoxColumn col = new GridViewComboBoxColumn("Value");
col.DataSource = EnumWrapper<EnumResultType>.EnumToList<EnumResultType>(); ;
col.DisplayMember = "Name";
col.ValueMember = "ID";
radGridView1.Columns.Add(col);
radGridView1.DataSource = table;