c#多选下拉框(ComboBox)
代码如下
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)的更多相关文章
- Easyui-Combobox多选下拉框
因为工作需要,引入combobox多选下拉框,并且获取选择的值并以","分开. 效果如下: 代码如下: <html> <head> <title> ...
- Extjs4.2 多选下拉框
//多选下拉框 Ext.define('MDM.view.custom.MultiComboBox', { extend: 'Ext.form.ComboBox', alias: 'widget.mu ...
- js多选下拉框
1.js原生实现 1.1:引用JS文件 /*! jQuery v1.12.4 | (c) jQuery Foundation | jquery.org/license */ !function(a,b ...
- c# 复选下拉框
引用dll: http://pan.baidu.com/s/1qXa97UO 自定义类: namespace TMI_S { /// <summary> /// 功能描述:自定义多选下拉框 ...
- ExtJs5.1多选下拉框CheckComb
ExtJs这么多个版本号了.可就是不提供多选下拉框,老外不用这个玩意吗? 5都出来这么久了,新写的项目就用5吧,把曾经Extjs4.2的时搜到前人的CheckComb改巴改巴.能用了就赶紧贴上来,没有 ...
- js:jquery multiSelect 多选下拉框实例
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- DropDownList单选与多选下拉框
一.单选DropDownList传值 1.添加界面的DropDownList显示值问题 (1)在方法内添加ViewData的方法: var ad = new UnitsRepository(); Vi ...
- pentaho cde 自定义复选下拉框 checkbox select
pentaho 自带的component 虽多,但是当用户需要在一个表格中查看多个组别的数据时,pentaho自带的单选框就不能实现了,所以复选下拉框势在必行,实现效果如下: 实现原理是借用了jqu ...
- Bootstrap3级联多选下拉框
<!DOCTYPE html> <html> <head> <title>Bootstrap3级联多选下拉框</title> <met ...
- js怎么能取得多选下拉框选中的多个值?
方法:获取多选下拉框对象数组→循环判断option选项的selected属性(true为选中,false为未选中)→使用value属性取出选中项的值.实例演示如下: 1.HTML结构 1 2 3 4 ...
随机推荐
- typeof + instanceof+toString+constructor什么推理javascript数据类型
一个.typeof JS这些变量是弱类型(这是弱类型)的,它可以不管用来存储数据的类型的. typeof 数据类型可用于检测给定的变量.可能的返回值: 1. 'undefined' --- 这个值没有 ...
- mysql_【MySQL】常见的mysql 进程state
Analyzing 线程是对MyISAM 表的统计信息做分析(例如, ANALYZE TABLE ). checking permissions 线程是检查服务器是否具有所需的权限来执行该语句. Ch ...
- 小程序大智慧,sqlserver 注释提取工具
原文:小程序大智慧,sqlserver 注释提取工具 开篇背景 我习惯在写表的创建脚本时将注释直接写在脚本里,比如 /*账套*/ CREATE TABLE [dbo].[AccountingBook] ...
- java_log4j 经典配置
程序加载制定日志文件 public static final String log4j = "log4j.xml"; /** * @declare 加载log4j * @throw ...
- iOS8开发~UI布局(二)storyboard中autolayout和size class的使用具体解释
一.概要:前一篇初步的描写叙述了size class的概念,那么实际中怎样使用呢,以下两个问题是我们一定会遇到的: 1.Xcode6中添加了size class,在storyboard中怎样使用? 2 ...
- [VirtualBox] - Install Oracle Linux 7 on Oracle VirtualBox
I'll start coding with JEE soon. Product environment adopts Oracle + WebLogic in Linux, technology a ...
- MonkeyRunner于Windows在下面Eclipse开发环境的搭建步骤(并解决在线Jython配置错误的问题)
网上有一shangdong_chu网友写了一篇文章介绍了如何Eclipse构造MonkeyRunner,他做了叙述一个很好的说明.但我对我的环境试验后会见Jython解析错误的问题,和制品缺少Pyde ...
- Objective-c中的单例
单例是指静态分配的实例,就是只开辟一块内存,不会重新开辟内存,而 iphone sdk 中全是这种实例,例如[UIApplication sharedApplication] 返回一个指向代表应用程序 ...
- Python超级明星WEB框架Flask
Flask简介 Flask是一个相对于Django而言轻量级的Web框架. 和Django大包大揽不同,Flask建立于一系列的开源软件包之上,这其中 最主要的是WSGI应用开发库Werkzeug和模 ...
- POJ 3928 & HDU 2492 Ping pong(树阵评价倒数)
主题链接: PKU:http://poj.org/problem?id=3928 HDU:http://acm.hdu.edu.cn/showproblem.php?pid=2492 Descript ...