ComboBoxListBox 在ComboBox控件里实现ListBox功能。如多选等。
ComboBoxListBox 源码:
public class ComboBoxListBox : ComboBox
{
private const int WM_LBUTTONDOWN = 0x201, WM_LBUTTONDBLCLK = 0x203;
ToolStripControlHost listBoxHost;
ToolStripDropDown dropDown;
private ListBox Lstbox = new ListBox();
public ComboBoxListBox()
{
}
public ListBox Set_ComboBoxListBox
{
set
{
Lstbox = value;
Lstbox.SelectedItems.Clear();
Lstbox.BorderStyle = BorderStyle.None;
Lstbox.SelectedIndexChanged += new EventHandler(Lstbox_SelectedIndexChanged);
Lstbox.SelectionMode = SelectionMode.MultiSimple;
listBoxHost = new ToolStripControlHost(Lstbox);
listBoxHost.AutoSize = false;
dropDown = new ToolStripDropDown();
dropDown.Width = this.Width;
dropDown.Items.Add(listBoxHost);
}
get
{
return Lstbox;
}
}
void Lstbox_SelectedIndexChanged(object sender, EventArgs e)
{
string StrSel = "";
for (int i = 0; i < Lstbox.SelectedItems.Count; i++)
{
StrSel += ((System.Data.DataRowView)Lstbox.SelectedItems[i])[Lstbox.ValueMember] + ",";
}
if (!string.IsNullOrEmpty(StrSel))
{
this.Text = StrSel.Substring(0, StrSel.Length - 1);
}
else
{
this.Text = "";
}
}
public CheckedListBox CheckedListBox
{
get { return listBoxHost.Control as CheckedListBox; }
}
private void ShowDropDown()
{
if (dropDown != null)
{
listBoxHost.Size = new Size(DropDownWidth - 2, DropDownHeight);
dropDown.Show(this, 0, this.Height);
}
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_LBUTTONDBLCLK || m.Msg == WM_LBUTTONDOWN)
{
ShowDropDown();
return;
}
base.WndProc(ref m);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (dropDown != null)
{
dropDown.Dispose();
dropDown = null;
}
}
base.Dispose(disposing);
}
}
用法:
Ds 为 DataSet
lst_Dept 为 在窗口里放置的一个ListBox
cbolst_Dept 为 ComboBoxListBox
lst_Dept.DataSource = Ds.Tables[0].DefaultView;
lst_Dept.DisplayMember = "DeptName";
lst_Dept.ValueMember = "DeptID";
cbolst_Dept.Set_ComboBoxListBox = lst_Dept;