views:

29

answers:

1

Here I have a code using ControlBuilder to make DropDown control generic.

[ControlBuilder(typeof(EnumDropDownControlBuilder))]
public class EnumDropDown : DropDownList {
    private string _enumType;
    private bool _allowEmpty;

    public string EnumType {
        get { return _EnumType; }
        set { _EnumType = value; }
    }

    public bool AllowEmpty {
        get { return _allowEmpty; }
        set { _allowEmpty= value; }
    }
}

public class EnumDropDown<T> : EnumDropDown where T : struct {
    public EnumDropDown() {
        this.Items.Clear();
        if (AllowEmpty) this.Items.Add(new ListItem("", "__EMPTY__"));
        foreach (string name in Enum.GetNames(typeof(T))) {
            Items.Add(name);
        }
    }

    public new T SelectedValue {
        get {
            if (IsEmpty) throw new NullReferenceException();
            return (T)Enum.Parse(typeof(T), base.SelectedValue, true);
        }
        set { base.SelectedValue = Enum.GetName(typeof(T), value); }
    }

    public bool IsEmpty {
        get {
            return base.SelectedValue == "__EMPTY__";
        }
        set { base.SelectedValue = Enum.GetName(typeof(T), value); }
    }
}

public class EnumDropDownControlBuilder : ControlBuilder {
    public override void Init(TemplateParser parser, ControlBuilder parentBuilder, Type type, string tagName, string id, IDictionary attribs) {

        string enumTypeName = (string)attribs["EnumType"];
        Type enumType = Type.GetType(enumTypeName);
        if (enumType == null) {
            throw new Exception(string.Format("{0} cannot be found or is not an enumeration", enumTypeName));
        }
        Type dropDownType = typeof(EnumDropDown<>).MakeGenericType(enumType);
        base.Init(parser, parentBuilder, dropDownType, tagName, id, attribs);
    }
}

Sorry the program is too long to read cheerfully.

The question is, although I defined property EnumType, AllowEmpty in class EnumDropDown. Since the real object created by ControlBuilder is EnumDropDown, values of EnumType, AllowEmpty are always null and false in control object. All attributes set in .aspx will be lost!

I can read attribute values of source tag in ControlBuilder. But I have no any idea how can I copy the attributes to the generic control object.

anyone can give me some hint?

A: 

It's so stupid that I tried to read value of properties in construtor public EnumDropDown() . Of course attributes are not setted since object is still constucting.

I rename constructor public EnumDropDown() to the method public void OnInit(EventArgs e), and all problem are fixed.

but