代码如下

 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. JavaScript--基于对象的脚本语言学习笔记(三)

    事件处理器 1.一个数据校验表单的例程 <html> <head> <title>js练习</title> <meta http-equiv=&q ...

  2. ASP.NET MVC+EF框架+EasyUI实现权限管理系列(16)-类库架构扩展以及DLL文件生成修改和用户的简单添加

    原文:ASP.NET MVC+EF框架+EasyUI实现权限管理系列(16)-类库架构扩展以及DLL文件生成修改和用户的简单添加 ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇) ...

  3. ASP.NET MVC+EF框架+EasyUI实现权限管理系列(11)-验证码实现和底层修改

    原文:ASP.NET MVC+EF框架+EasyUI实现权限管理系列(11)-验证码实现和底层修改 ASP.NET MVC+EF框架+EasyUI实现权限管系列  (开篇)   (1):框架搭建    ...

  4. springmvc4

    web项目(使用html视图解析器)   完整配置springmvc4,最终视图选择的是html,非静态文件. 最近自己配置spring的时候,遇到很多问题,由于开发环境和版本的变化导致网友们给出的建 ...

  5. 杭电1162Eddy&#39;s picture

    Eddy's picture Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other) Tota ...

  6. php_中替换换行符

    //php 有三种方法来解决 //1.使用str_replace 来替换换行 $str = str_replace(array("\r\n", "\r", &q ...

  7. spring data jpa使用懒操作

    如果model对象的某属性使用lazy load,调用这个属性时会报错, failed to lazily initialize a collection of role could not init ...

  8. 如何快速正确的安装 Ruby, Rails 运行环境

    如何快速正确的安装 Ruby, Rails 运行环境 https://ruby-china.org/wiki/install_ruby_guide 对于新入门的开发者,如何安装 Ruby, Ruby ...

  9. linux Packet socket (1)简单介绍

    本文主要来自于linux自带的man packet手冊: http://man7.org/linux/man-pages/man7/packet.7.html 平时常常使用的INET套接字提供的是7层 ...

  10. Fluent Validation + NInject3 + MVC5

    Fluent Validation + NInject + MVC - Why & How : Part 1 http://fluentvalidation.codeplex.com/ htt ...