数据组合框






4.81/5 (6投票s)
一个自定义组合框控件,
引言
这是一个使用自定义控件在下拉框中显示多列的示例。它使用 DataTable
作为其数据源,与标准的下拉框不同,它可以显示多列,从而显示更多信息。它继承自 System.Windows.Forms.Combobox
类。
背景
该项目基于 SeeSharp 在他的 多列下拉框 文章中的一个想法。我使用了相同的概念,即继承一个 Combobox
并重写 OnDropDown
事件,以启动包含 DataGridView
的表单。我最初打算只创建一个 DLL 类,但我讨厌需要其他 DLL 的 EXE。我更喜欢将所有内容编译在一起。考虑到这一点,我希望使将控件包含在项目中变得简单。因此,我将我的两个表单合并到一个类中。
Using the Code
您只需要两个文件
- DataCombobox.cs,和
- DataCombobox.Designer.cs
将类文件 DataCombobox.cs 添加到您的项目中。这应该也会自动添加 DataCombobox.Designer.cs。
将以下行...
using datacombobox;
... 放入您的表单中,然后重新生成您的解决方案。这将使自定义控件出现在工具箱中,以便您可以将其拖动到您的表单上。
这是一个关于如何使用它的示例代码。
DataTable tbl = new DataTable();
tbl.Columns.Add("code", System.Type.GetType("System.String"));
tbl.Columns.Add("desc", System.Type.GetType("System.String"));
tbl.Columns.Add("other1", System.Type.GetType("System.String"));
tbl.Rows.Add("aaa", "the a thing", "");
tbl.Rows.Add("code2", "code #2", "");
tbl.Rows.Add("code3", "code #3", "");
tbl.Rows.Add("code4", "code #4", "just a code");
tbl.Rows.Add("widget", "some sort of device", "");
tbl.Rows.Add("code5", "code #5", "");
tbl.Rows.Add("rush", "awesome rock group", "");
tbl.AcceptChanges();
//these are required
dataCombobox1.TblData = tbl;
dataCombobox1.ValueColumn = "code";
dataCombobox1.SetText("widget");
//these are optional
//by default you will see all the columns in your table
//use ColumnNameList to make it show just certain columns
//this is a pipe delimited list
dataCombobox1.ColumnNameList = "code|desc";
//use ColumnHeaderList to define the text that show in the column headers
dataCombobox1.ColumnHeaderList = "Code|Description";
//you can control the width of the columns
dataCombobox1.WidthList = "50|200";
//you can control the width and height of the grid
dataCombobox1.PopupWidth = 300;
dataCombobox1.PopupHeight = 200;
DataCombobox
在您单击下拉按钮之前,看起来就像一个普通的 Combobox
。您也可以按向下箭头键来获取下拉列表。

另一个有用的属性是 SearchColumn
属性。通常,按字母键会在 ValueColumn
字段中进行搜索。但是,您可以设置 SearchColumn
属性,并且搜索将在该列中进行。例如,您可能希望搜索描述而不是实际代码。
请在源代码中查找一个简单的示例项目。
关注点
我在处理按键搜索代码时发现的一个陷阱是,您必须小心使用正确的对象。最初,我搜索 DataTable
的行,然后使用该位置编号在 DataGridView
中选择一行。但是,存在的问题是表中的行顺序可能与 DataGridView
中的顺序不同。用户可以单击列标题并随时更改屏幕上的排序顺序。因此,我必须按 DataGridView
本身的行进行搜索。您必须记住,即使 DataGridView
的 DataSource
设置为 DataTable
,在 DataGridView
中选择的行号也不会指向 DataTable
中的该行。它们是两种不同类型的行。
历史
- 2010 年 7 月 25 日:初始版本