C# WinForm下拉TreView

winform没有默认的下拉tree的控件可是有些多级的列表需要下拉tree,下面我们的代码实现对Combbox进行扩展让它下拉显示tree.

  1. using System.Drawing;  
  2. using System.Windows.Forms;  
  3. namespace WindowsApplication23  
  4. {  
  5.     public class ComboBoxTreeView : ComboBox  
  6.     {  
  7.         private const int WM_LBUTTONDOWN = 0x201, WM_LBUTTONDBLCLK = 0x203;  
  8.         ToolStripControlHost treeViewHost;  
  9.         ToolStripDropDown dropDown;  
  10.         public ComboBoxTreeView()  
  11.         {  
  12.             TreeView treeView = new TreeView();  
  13.             treeView.AfterSelect += new TreeViewEventHandler(treeView_AfterSelect);  
  14.             treeView.BorderStyle = BorderStyle.None;  
  15.   
  16.             treeViewHost = new ToolStripControlHost(treeView);  
  17.             dropDown = new ToolStripDropDown();  
  18.             dropDown.Width = this.Width;  
  19.             dropDown.Items.Add(treeViewHost);  
  20.         }  
  21.         public void treeView_AfterSelect(object sender, TreeViewEventArgs e)  
  22.         {  
  23.             this.Text = TreeView.SelectedNode.Text;  
  24.             dropDown.Close();  
  25.         }  
  26.         public TreeView TreeView  
  27.         {  
  28.             get { return treeViewHost.Control as TreeView; }  
  29.         }  
  30.         private void ShowDropDown()  
  31.         {  
  32.             if (dropDown != null)  
  33.             {  
  34.                 treeViewHost.Size = new Size(DropDownWidth - 2, DropDownHeight);  
  35.                 dropDown.Show(this, 0, this.Height);  
  36.             }  
  37.         }  
  38.         protected override void WndProc(ref Message m)  
  39.         {  
  40.             if (m.Msg == WM_LBUTTONDBLCLK || m.Msg == WM_LBUTTONDOWN)  
  41.             {  
  42.                 ShowDropDown();  
  43.                 return;  
  44.             }  
  45.             base.WndProc(ref m);  
  46.         }  
  47.         protected override void Dispose(bool disposing)  
  48.         {  
  49.             if (disposing)  
  50.             {  
  51.                 if (dropDown != null)  
  52.                 {  
  53.                     dropDown.Dispose();  
  54.                     dropDown = null;  
  55.                 }  
  56.             }  
  57.             base.Dispose(disposing);  
  58.         }  
  59.     }  
  60.   
这只是一个简单的实现,后面我们会把它显示到dataGrid里面。*[电13802269370]  北京*[电13802269370]  郑州*[电13802269370]  深圳*[电13802269370]
上一篇:javascript-将HTML select元素变成带有子菜单的树


下一篇:Cnblog-Latex数学公式使用测试