泛型与反射机制处理ComBox绑定的数据源是List<实体对象>

 今天在做把传统的ComBox绑定的数据源是List<实体对象>,有很多的页面都是这么处理的,而且实体类不同.

心想不能每个页面都吧,后来就想着用泛型与反射机制处理:才写出了这个通用的方法如下:

这可以偶花了好几个小时的心血哦,有需要的直接拿去用吧。而且以这个为例也可变化出很多的用法。大家快来学习一下吧!

  #region public static void SetComboBoxData(DevExpress.XtraEditors.ImageComboBoxEdit comboBox,List<T> list, string valueMember, string displayMember, string selectedText = null)
        /// <summary>
        /// 绑定下拉框
        /// </summary>
        /// <param name="comboBox">下拉控件</param>
        /// <param name="List<T> ">实体集合</param>
        /// <param name="valueMember">值字段</param>
        /// <param name="displayMember">显示字段</param>
        /// <param name="selectedText">默认选中的值</param>
        public static void SetComboBoxData<T>(DevExpress.XtraEditors.ImageComboBoxEdit comboBox, List<T> list, string valueMember, string displayMember, string selectedText = null)//
        {
            comboBox.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            comboBox.Properties.NullText = string.Empty;
        
            foreach (var item in list)
            {
                comboBox.Properties.Items.Add(new ImageComboBoxItem(item.GetType().GetProperty(valueMember).GetValue(item, null).ToString(), item.GetType().GetProperty(valueMember).GetValue(item, null).ToString()));
            }

            // //这里是设置默认选中的值
            if (!string.IsNullOrEmpty(selectedText))
            {
                comboBox.SelectedItem = comboBox.Properties.Items.GetItem(selectedText);
            }
        }
        #endregion

原文地址:https://www.cnblogs.com/spring_wang/p/3072640.html