Samstag, 19. Januar 2008

Dot Net (C#): Enum in Combobox

Folgende Methode ermöglicht es, alle Elemente einer Enumeration in einer Combobox anzuzeigen:

private void importEnumeration(Type t)
{
this.comboBox.Items.Clear();
this.comboBox.Items.AddRange(Enum.GetNames(t));
this.comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
this.comboBox.SelectedIndex = 0;
}

Aufruf:

this.importEnumeration(typeof(anyEnum));

1 Kommentar:

Kirill Osenkov hat gesagt…

Nett!

Man kann die Methode auch generisch machen:

private void importEnumeration<T>(){ this.comboBox.Items.Clear(); this.comboBox.Items.AddRange(Enum.GetNames(typeof(T))); this.comboBox.DropDownStyle = ComboBoxStyle.DropDownList; this.comboBox.SelectedIndex = 0;}

Aufruf:

this.importEnumeration<anyEnum>();