load绑定下拉框的内容

在窗体加载的时候,下拉框需要绑定从数据库获取的内容  对dropZT控件进行绑定

BZXXWH entity = new BZXXWH();
ServiceResult<List<BZXXWH>> result = WCFClient.BZXXWH_QueryMainList(entity);
if (result != null && result.Code == enumServiceResultCode.Success)
{
  ComboBoxEditEx.BindComBox<BZXXWH>(dropZT, result.Data, "BiZhong", "BiZhong");
}

WCFClient.BZXXWH_QueryMainList(entity);里面是sql语句

 

BindComBox  写绑定方法

/// <summary>
/// 使用指定数据源绑定下拉列表框
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dropdownList">待绑定下拉列表框</param>
/// <param name="dataList">数据源</param>
/// <param name="displayField">下拉选项显示字段名称 数据源实例公开属性</param>
/// <param name="valueField">下拉选项值 数据源实例公开属性</param>
/// <param name="defaultText">默认选项信息</param>
public static void BindComBox<T>(ComboBoxEditEx dropdownList, List<T> dataList,string displayField,string valueField, string defaultText = DefaultEmptyItem) where T: class
{
dropdownList.Properties.Items.Clear();
if (!string.IsNullOrWhiteSpace(defaultText))
{
dropdownList.Properties.Items.Add(new DictionaryClass(defaultText, ""));
}
if (dataList != null && dataList.Count > 0)
{
Type aimType = typeof(T);
PropertyInfo displayPropertyInfo = aimType.GetProperty(displayField, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (displayPropertyInfo == null)
throw new Exception("查找属性失败:" + displayField);
PropertyInfo valuePropertyInfo = aimType.GetProperty(valueField, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (valuePropertyInfo == null)
throw new Exception("查找属性失败:" + valueField);
object tempObj = null;
string tempText = null;
string tempValue = null;
List<string> existValue = new List<string>();
foreach (var item in dataList)
{
tempObj = displayPropertyInfo.GetValue(item,null);
tempText = tempObj == null ? "": tempObj.ToString();
tempObj = valuePropertyInfo.GetValue(item, null);
tempValue = tempObj == null ? "" : tempObj.ToString();
if (existValue.Contains(tempValue))
throw new Exception($"下拉框选项值{tempValue}重复存在");
dropdownList.Properties.Items.Add(new DictionaryClass(tempText, tempValue,item));
}
}
dropdownList.SelectedIndex = 0;
dropdownList.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
}

 

posted on 2019-08-28 15:01  伍佰仟  阅读(90)  评论(0)    收藏  举报