Add empty item to dropdownlist of custom objects in C#

前端 未结 4 2052
生来不讨喜
生来不讨喜 2021-01-05 12:09

We are binding a list of custom objects to an ASP.NET DropDownList in C# but we want to allow for the DropDownList to not have anything selected initially. One way of doing

4条回答
  •  春和景丽
    2021-01-05 12:37

    Just working on this actually, here's what I got so far (along with a couple databinding goodies)

    public interface ICanBindToObjectsKeyValuePair {
        void BindToProperties(IEnumerable bindableEnumerable, Expression> textProperty, Expression> valueProperty);
    }
    
    public class EasyBinderDropDown : DropDownList, ICanBindToObjectsKeyValuePair {
        public EasyBinderDropDown() {
            base.AppendDataBoundItems = true;
        }
        public void BindToProperties(IEnumerable bindableEnumerable,
            Expression> textProperty, Expression> valueProperty) {
            if (ShowSelectionPrompt)
                Items.Add(new ListItem(SelectionPromptText, SelectionPromptValue));
            base.DataTextField = textProperty.MemberName();
            base.DataValueField = valueProperty.MemberName();
            base.DataSource = bindableEnumerable;
            base.DataBind();
        }
        public bool ShowSelectionPrompt { get; set; }
        public string SelectionPromptText { get; set; }
        public string SelectionPromptValue { get; set; }
        public virtual IEnumerable ListItems {
            get { return Items.Cast(); }
        }
    }
    

    Notice one thing that you can do is

    dropDown.BindToProperties(myCustomers, c=>c.CustomerName, c=>c.Id);
    

提交回复
热议问题