代码如下

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;
using Newtonsoft.Json.Linq; namespace ControlsAA
{
public class ComboBoxEx : ComboBox
{
TreeView lst = new TreeView(); public ComboBoxEx()
{
this.DrawMode = DrawMode.OwnerDrawFixed;//只有设置这个属性为OwnerDrawFixed才可能让重画起作用
lst.KeyUp += new KeyEventHandler(lst_KeyUp);
lst.MouseUp += new MouseEventHandler(lst_MouseUp);
// lst.KeyDown += new KeyEventHandler(lst_KeyDown);
lst.Leave += new EventHandler(lst_Leave);
lst.CheckBoxes = true;
lst.ShowLines = false;
lst.ShowPlusMinus = false;
lst.ShowRootLines = false;
this.DropDownHeight = ;
} void lst_Leave(object sender, EventArgs e)
{
lst.Hide();
}
#region Property [Description("选定项的值"), Category("Data")]
public List<TreeNode> SelectedItems
{
get
{
List<TreeNode> lsttn = new List<TreeNode>();
foreach (TreeNode tn in lst.Nodes)
{
if (tn.Checked)
{
lsttn.Add(tn);
}
}
return lsttn;
}
} /// <summary>
/// 数据源
/// </summary>
[Description("数据源"), Category("Data")]
public object DataSource
{
get;
set;
}
/// <summary>
/// 显示字段
/// </summary>
[Description("显示字段"), Category("Data")]
public string DisplayFiled
{
get;
set;
}
/// <summary>
/// 值字段
/// </summary>
[Description("值字段"), Category("Data")]
public string ValueFiled
{
get;
set;
}
#endregion public void DataBind()
{
this.BeginUpdate();
if (DataSource != null)
{
if (DataSource is IDataReader)
{
DataTable dataTable = new DataTable();
dataTable.Load(DataSource as IDataReader); DataBindToDataTable(dataTable);
}
else if (DataSource is DataView || DataSource is DataSet || DataSource is DataTable)
{
DataTable dataTable = null; if (DataSource is DataView)
{
dataTable = ((DataView)DataSource).ToTable();
}
else if (DataSource is DataSet)
{
dataTable = ((DataSet)DataSource).Tables[];
}
else
{
dataTable = ((DataTable)DataSource);
} DataBindToDataTable(dataTable);
}
else if (DataSource is IEnumerable)
{
DataBindToEnumerable((IEnumerable)DataSource);
}
else
{
throw new Exception("DataSource doesn't support data type: " + DataSource.GetType().ToString());
}
}
else
{
lst.Nodes.Clear();
} lst.ItemHeight = this.ItemHeight;
lst.BorderStyle = BorderStyle.FixedSingle;
lst.Size = new Size(this.DropDownWidth, this.ItemHeight * (this.MaxDropDownItems - ) - (int)this.ItemHeight / );
lst.Location = new Point(this.Left, this.Top + this.ItemHeight + );
this.Parent.Controls.Add(lst);
lst.Hide();
this.EndUpdate();
} private void DataBindToDataTable(DataTable dt)
{
foreach (DataRow dr in dt.Rows)
{
TreeNode tn = new TreeNode();
if (!string.IsNullOrEmpty(DisplayFiled) && !string.IsNullOrEmpty(ValueFiled))
{
tn.Text = dr[DisplayFiled].ToString();
tn.Tag = dr[ValueFiled].ToString();
}
else if (string.IsNullOrEmpty(ValueFiled))
{
tn.Text = dr[DisplayFiled].ToString();
tn.Tag = dr[DisplayFiled].ToString();
}
else if (string.IsNullOrEmpty(DisplayFiled))
{
tn.Text = dr[ValueFiled].ToString();
tn.Tag = dr[ValueFiled].ToString();
}
else
{
throw new Exception("ValueFiled和DisplayFiled至少保证有一项有值");
} tn.Checked = false;
lst.Nodes.Add(tn);
}
} /// <summary>
/// 绑定到可枚举类型
/// </summary>
/// <param name="enumerable">可枚举类型</param>
private void DataBindToEnumerable(IEnumerable enumerable)
{
IEnumerator enumerator = enumerable.GetEnumerator();
while (enumerator.MoveNext())
{
object currentObject = enumerator.Current;
lst.Nodes.Add(CreateListItem(currentObject));
}
} private TreeNode CreateListItem(Object obj)
{
TreeNode item = new TreeNode(); if (obj is string)
{
item.Text = obj.ToString();
item.Tag = obj.ToString();
}
else
{
if (DisplayFiled != "")
{
item.Text = GetPropertyValue(obj, DisplayFiled);
}
else
{
item.Text = obj.ToString();
} if (ValueFiled != "")
{
item.Tag = GetPropertyValue(obj, ValueFiled);
}
else
{
item.Tag = obj.ToString();
}
}
return item;
} private string GetPropertyValue(object obj, string propertyName)
{
object result = null; result = ObjectUtil.GetPropertyValue(obj, propertyName);
return result == null ? String.Empty : result.ToString();
} #region override protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyDown(e);
bool Pressed = (e.Control && ((e.KeyData & Keys.A) == Keys.A));
if (Pressed)
{
this.Text = "";
for (int i = ; i < lst.Nodes.Count; i++)
{
lst.Nodes[i].Checked = true;
if (this.Text != "")
{
this.Text += ",";
}
this.Text += lst.Nodes[i].Tag;
}
}
} protected override void OnMouseDown(MouseEventArgs e)
{
this.DroppedDown = false; } protected override void OnMouseUp(MouseEventArgs e)
{
this.DroppedDown = false;
lst.Focus();
} protected override void OnDropDown(EventArgs e)
{
string strValue = this.Text;
if (!string.IsNullOrEmpty(strValue))
{
List<string> lstvalues = strValue.Split(',').ToList<string>();
foreach (TreeNode tn in lst.Nodes)
{
if (tn.Checked && !lstvalues.Contains(tn.Tag.ToString()) && !string.IsNullOrEmpty(tn.Tag.ToString().Trim()))
{
tn.Checked = false;
}
else if (!tn.Checked && lstvalues.Contains(tn.Tag.ToString()) && !string.IsNullOrEmpty(tn.Tag.ToString().Trim()))
{
tn.Checked = true;
}
}
} lst.Show(); }
#endregion private void lst_KeyUp(object sender, KeyEventArgs e)
{
this.OnKeyUp(e);
} private void lst_MouseUp(object sender, MouseEventArgs e)
{
try
{
this.Text = "";
for (int i = ; i < lst.Nodes.Count; i++)
{
if (lst.Nodes[i].Checked)
{
if (this.Text != "")
{
this.Text += ",";
}
this.Text += lst.Nodes[i].Tag;
}
}
}
catch
{
this.Text = "";
}
bool isControlPressed = (Control.ModifierKeys == Keys.Control);
bool isShiftPressed = (Control.ModifierKeys == Keys.Shift);
if (isControlPressed || isShiftPressed)
lst.Show();
else
lst.Hide();
} } /// <summary>
/// 对象帮助类
/// </summary>
public class ObjectUtil
{
/// <summary>
/// 获取对象的属性值
/// </summary>
/// <param name="obj">可能是DataRowView或一个对象</param>
/// <param name="propertyName">属性名</param>
/// <returns>属性值</returns>
public static object GetPropertyValue(object obj, string propertyName)
{
object result = null; try
{
if (obj is DataRow)
{
result = (obj as DataRow)[propertyName];
}
else if (obj is DataRowView)
{
result = (obj as DataRowView)[propertyName];
}
else if (obj is JObject)
{
result = (obj as JObject).Value<JValue>(propertyName).Value; //.getValue(propertyName);
}
else
{
result = GetPropertyValueFormObject(obj, propertyName);
}
}
catch (Exception)
{
// 找不到此属性
} return result;
} /// <summary>
/// 获取对象的属性值
/// </summary>
/// <param name="obj">对象</param>
/// <param name="propertyName">属性名("Color"、"BodyStyle"或者"Info.UserName")</param>
/// <returns>属性值</returns>
private static object GetPropertyValueFormObject(object obj, string propertyName)
{
object rowObj = obj;
object result = null; if (propertyName.IndexOf(".") > )
{
string[] properties = propertyName.Split('.');
object tmpObj = rowObj; for (int i = ; i < properties.Length; i++)
{
PropertyInfo property = tmpObj.GetType().GetProperty(properties[i], BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (property != null)
{
tmpObj = property.GetValue(tmpObj, null);
}
} result = tmpObj;
}
else
{
PropertyInfo property = rowObj.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (property != null)
{
result = property.GetValue(rowObj, null);
}
} return result;
}
}
}

需要引用的文件在这里http://pan.baidu.com/s/1qXa97UO

c#多选下拉框(ComboBox)的更多相关文章

  1. Easyui-Combobox多选下拉框

    因为工作需要,引入combobox多选下拉框,并且获取选择的值并以","分开. 效果如下: 代码如下: <html> <head> <title> ...

  2. Extjs4.2 多选下拉框

    //多选下拉框 Ext.define('MDM.view.custom.MultiComboBox', { extend: 'Ext.form.ComboBox', alias: 'widget.mu ...

  3. js多选下拉框

    1.js原生实现 1.1:引用JS文件 /*! jQuery v1.12.4 | (c) jQuery Foundation | jquery.org/license */ !function(a,b ...

  4. c# 复选下拉框

    引用dll: http://pan.baidu.com/s/1qXa97UO 自定义类: namespace TMI_S { /// <summary> /// 功能描述:自定义多选下拉框 ...

  5. ExtJs5.1多选下拉框CheckComb

    ExtJs这么多个版本号了.可就是不提供多选下拉框,老外不用这个玩意吗? 5都出来这么久了,新写的项目就用5吧,把曾经Extjs4.2的时搜到前人的CheckComb改巴改巴.能用了就赶紧贴上来,没有 ...

  6. js:jquery multiSelect 多选下拉框实例

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  7. DropDownList单选与多选下拉框

    一.单选DropDownList传值 1.添加界面的DropDownList显示值问题 (1)在方法内添加ViewData的方法: var ad = new UnitsRepository(); Vi ...

  8. pentaho cde 自定义复选下拉框 checkbox select

    pentaho  自带的component 虽多,但是当用户需要在一个表格中查看多个组别的数据时,pentaho自带的单选框就不能实现了,所以复选下拉框势在必行,实现效果如下: 实现原理是借用了jqu ...

  9. Bootstrap3级联多选下拉框

    <!DOCTYPE html> <html> <head> <title>Bootstrap3级联多选下拉框</title> <met ...

  10. js怎么能取得多选下拉框选中的多个值?

    方法:获取多选下拉框对象数组→循环判断option选项的selected属性(true为选中,false为未选中)→使用value属性取出选中项的值.实例演示如下: 1.HTML结构 1 2 3 4 ...

随机推荐

  1. 全排列 ( next_permutation)

    SLT: C++的STL有一个函数可以方便地生成全排列,这就是next_permutation 在C++ Reference中查看了一下next_permutation的函数声明: #include ...

  2. Babelfish (STL)

    题目描述 You have just moved from Waterloo to a big city. The people here speak an incomprehensible dial ...

  3. ASP.NET MVC+EF框架+EasyUI实现权限管理系列(18)-过滤器的使用和批量删除数据(伪删除和直接删除)

    原文:ASP.NET MVC+EF框架+EasyUI实现权限管理系列(18)-过滤器的使用和批量删除数据(伪删除和直接删除) ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇)   ...

  4. hdu 游乐场

    Problem Description   小时候,因为家里经济困难,小明从未去过游乐场,所以直到现在,他还心存遗憾.  最近,杭州刚建了一座游乐场,为了弥补儿时的遗憾,小明带了一笔钱迫不及待地要去体 ...

  5. Openstack本学习笔记——Neutron-server服务加载和启动源代码分析(三)

    本文是在学习Openstack过程中整理和总结.因为时间和个人能力有限.错误之处在所难免,欢迎指正! 在Neutron-server服务载入与启动源代码分析(二)中搞定模块功能的扩展和载入.我们就回到 ...

  6. VTune使用amplxe-cl进行Hardware Event-based Sampling Analysis 0分析

    于BASH正在使用VTune进行Hardware Event-based Sampling Analysis 0分析: 结果(部分)例如以下: 版权声明:本文博客原创文章.博客,未经同意,不得转载.

  7. Vs2012 构建配置 Lua5.2.3

    随着手机游戏client程序员,当然,遇到这样的问题,该游戏已经提交出版.但第二天一早,发现有一个逻辑游戏BUG.怎么办,不严重,在一般情况下,非强制性的更新.假设一个严重BUG,他们将不得不强制更新 ...

  8. PHP的垃圾回收机制详解

    原文:PHP的垃圾回收机制详解 最近由于使用php编写了一个脚本,模拟实现了一个守护进程,因此需要深入理解php中的垃圾回收机制.本文参考了PHP手册. 在理解PHP垃圾回收机制(GC)之前,先了解一 ...

  9. javascript常用知识点集

    javascript常用知识点集 目录结构 一.jquery源码中常见知识点 二.javascript中原型链常见的知识点 三.常用的方法集知识点 一.jquery源码中常见的知识点 1.string ...

  10. Entity Framework查询原理

    Entity Framework查询原理 前言 Entity Framework的全称是ADO.NET Entity Framework,是微软开发的基于ADO.NET的ORM(Object/Rela ...