Passing strongly typed property name as argument

后端 未结 3 1185
春和景丽
春和景丽 2020-12-30 17:37

I have a collection of IEnumerable that is being passed to an extension method that populates a DropDownList. I would also like to pa

3条回答
  •  天命终不由人
    2020-12-30 17:58

    With what you were trying, even if you did get it to compile/run, it would still be wrong because the Value & Text fields would've been set to a value in the list instead of the property name (ie, DataValueField = "TX"; DataTextField = "Texas"; instead of DataValueField = "stateCode"; DataTextField = "stateName"; like you really want).

    public static void populateDropDownList(this DropDownList source,
            IEnumerable dataSource,
            Func dataValueField,
            Func dataTextField) {
        source.DataValueField = dataValueField();
        source.DataTextField = dataTextField();
        source.DataSource = dataSource;
        source.DataBind();
    }
    
    myDropDownList.populateDropDownList(states,
            "stateCode",
            "stateName");
    

提交回复
热议问题