I am trying to populate 2 comboboxes using reflection. The first combobox (called ObjectTypes) contains: Table, View and Field values
The second combobox (called PropertiesComboBox) is populated according to the selection on the first combobox.
The comboboxes are populated from a repository:
public class ObjectType
{
[Displayed]
public Table Table { get; private set; }
[Displayed]
public Field Field { get; private set; }
[Displayed]
public View View { get; private set; }
}
public class Table
{
[Displayed]
public Name Name { get; private set; }
[Displayed]
public Description Description { get; private set; }
}
public class Field
{
[Displayed]
public Name Name { get; private set; }
[Displayed]
public Description Description { get; private set; }
}
public class View
{
[Displayed]
public Name Name { get; private set; }
[Displayed]
public Description Description { get; private set; }
[Displayed]
public Query Query { get; private set; }
}
public class Name
{
}
public class Description
{
}
public class Query
{
}
public class Displayed : Attribute
{
}
I added a custom attribute on all the properties in order to get only the properties defined on the above classes and prevent from "system" attributes to be retrieved.
In order to populate the first combobox:
private void PopulateObjectsType()
{
Type type = typeof(ObjectType);
var properties = type.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(Displayed)));
foreach (PropertyInfo propertyInfo in properties)
{
ObjectsTypeComboBox.Items.Add(propertyInfo);
}
}
In order to populate the second combobox:
private void ObjectsTypeComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
var objectType = ObjectsTypeComboBox.SelectedItem;
Type type = objectType.GetType();
var properties = type.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(Displayed)));
foreach (PropertyInfo propertyInfo in properties)
{
PropertiesComboBox.Items.Add(propertyInfo.Name);
}
}
I have two issues:
- The first combobox is showing the namespace concatenate with the name of the class (e.g. [namespace] + [Table]. How can I show only the name of the class?
- After selecting an item from the first combobox, in ObjectsTypeComboBox_SelectedIndexChanged the properties return null since the CustomAttribute [Displayed] is not found. Why is that?
Aucun commentaire:
Enregistrer un commentaire