以前看过许多数据库编程都有数据检索的控件,这次在项目也同样遇到需要这样的东东,在网上找了一没找到,只好自己用C#来丰衣足食了。

控件功能需求:用户通过录入关键字,控件根据录入关键字自动进行检索,显示检索记录集.

组合控件各控件功能:
   TextBox 用于给用户录入关键字,当按向下键时Form.DataGrid获得焦点.
   Form是在当TextBox发生TextChange时显示.当用户点击控件所在窗体基它位置时,Form隐藏。
   DataGrid根据关键字检索数据记录并显示.当在DataGrid按非功能键时(向上,向下,向左,向右,回车)
   TextBox便获得焦点,并得到相应按键信息.  

具体代码:
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Runtime;
 
namespace Controller
{
 /// <summary>
 /// DanWeiComboBox 的摘要说明。
 /// </summary>
 /// <remarks>
 /// Created by chs  2005-08-29, Last changes: 10/09/2005
 /// </remarks>
 public class FindDataTextBox : System.Windows.Forms.UserControl
 {

 

  private FrmDataList  _ListDataGrid =null;
  /// <summary>
  /// 数据源
  /// </summary>
  private DataTable  _DataSource ;
  /// <summary>
  /// 排序的列名
  /// </summary>
  private string _SortColumnName =null;

 

  private DataView dv =null;
  /// <summary>
  /// 筛选表达式
  /// </summary>
  private string _RowFilterExpression =null ;


  public  System.Windows.Forms.TextBox tb_KeyValue;

  /// <summary>
  /// 排序的列名
  /// </summary>
  public string SortColumnName
  {
   set
   {
    this._SortColumnName=value;
   }
  }


  /// <summary>
  /// 筛选表达式
  /// </summary>
  public string RowFilterExpression
  {
   set
   {
    this._RowFilterExpression=value;
   }
  }
  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private System.ComponentModel.Container components = null;

  private FrmDataList  ListDataGrid
  {
   get { 
    if ( _ListDataGrid !=null)
     return _ListDataGrid ;
    else
    {
     this._ListDataGrid=new FrmDataList();
     _ListDataGrid.Location=new Point(this.Parent.Location.X +this.Location.X +this.tb_KeyValue.Location.X+this.Width,this.Parent.Location.Y +this.Location.Y +this.tb_KeyValue.Location.Y +this.Height);
     _ListDataGrid.MyGetFormKeyPress +=new GetFormKeyPress(_ListDataGrid_MyGetFormKeyPress);
     this.FindForm().AddOwnedForm(_ListDataGrid);
     this.ListDataGrid.mySetControl +=new SetOutControl(ListDataGrid_mySetControl);
     this.FindForm().Click +=new EventHandler(DanWeiComboBox_Click);
     return this._ListDataGrid;
    }
   }
  }

 
  public DataTable DataSource
  {
   set {this. _DataSource =value;}
   get {return  _DataSource ; }

  }
  
  private string _DisplayMember;
  public string  DisplayItem
  {
   set {
   
    _DisplayMember=value.ToString();
    
   }

   get {

    return _DisplayMember ;
   }
  }

  
  /// <summary>
  /// 获取选中的值
  /// </summary>
  public object  SelectValue
  {
   get
   {
    return this.tb_KeyValue.Tag ;
   }
  }

  /// <summary>
  /// 获取选中的文本
  /// </summary>
  public object SelectText
  {
   get
   {
    return this.tb_KeyValue.Text ;
    
   }
  }

  private string _ValueMember;
  public string  ValueItem
  {
   set {
    _ValueMember =value.ToString();
   }

   get
   {

    return _ValueMember ;
   }
  }

  public FindDataTextBox()
  {
   // 该调用是 Windows.Forms 窗体设计器所必需的。
   InitializeComponent();

   // TODO: 在 InitializeComponent 调用后添加任何初始化

  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if(components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region 组件设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器
  /// 修改此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.tb_KeyValue = new System.Windows.Forms.TextBox();
   this.SuspendLayout();
   //
   // tb_KeyValue
   //
   this.tb_KeyValue.Location = new System.Drawing.Point(4, 2);
   this.tb_KeyValue.Name = "tb_KeyValue";
   this.tb_KeyValue.Size = new System.Drawing.Size(200, 21);
   this.tb_KeyValue.TabIndex = 0;
   this.tb_KeyValue.Text = "textBox1";
   this.tb_KeyValue.TextChanged += new System.EventHandler(this.tb_KeyValue_TextChanged);
   //
   // DanWeiComboBox
   //
   this.Controls.Add(this.tb_KeyValue);
   this.Name = "FindDataTextBox";
   this.Size = new System.Drawing.Size(224, 24);
   this.Leave += new System.EventHandler(this.tb_KeyValue_LostFocus);
   this.ResumeLayout(false);

  }
  #endregion

  private void tb_KeyValue_TextChanged(object sender, System.EventArgs e)
  {
   
   if (this.tb_KeyValue.Focused)
   { 
    this.SetListDataGridDataSource();
    ListDataGrid.Visible=true;
    SetActiveControl();
   }
   

   
  }
 

  /// <summary>
  /// 设置活动控件
  /// </summary>
  private void  SetActiveControl()
  {
   this.ActiveControl=this.tb_KeyValue ;
   if (this.tb_KeyValue.Text!=null && this.tb_KeyValue.Text.Trim().Length >0)
   {
    this.tb_KeyValue.SelectionStart=this.tb_KeyValue.Text.ToString().Length;
   }

  }
  /// <summary>
  /// 筛选数据绑定到ListDataGrid
  /// </summary>
  private void SetListDataGridDataSource()
  {
   string str =String.Format(this._RowFilterExpression,this.tb_KeyValue.Text.ToString().Trim()) ;
   dv =new DataView(this.DataSource,str,this._SortColumnName ,System.Data.DataViewRowState.CurrentRows) ;
   this.ListDataGrid.dataGrid1.DataSource=null;
   this.ListDataGrid.dataGrid1.DataSource= dv;
    
  }

  private void tb_KeyValue_LostFocus(object sender, EventArgs e)
  {

   if (this.ListDataGrid.dataGrid1.Focused==false )
    this.ListDataGrid.Visible=false;
  }

  protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
  {
   if (keyData==Keys.Down &&this.dv !=null &&  this.dv.Count>=1 )
   {
    this.ListDataGrid.Focus();
    
    return true;
   }
   else
   {
    return base.ProcessCmdKey (ref msg, keyData);
   }
  }


  private void ListDataGrid_mySetControl(ref Message msg, Keys KeyData)
  { 
   this.SetActiveControl();
 
  }

  private void DanWeiComboBox_Click(object sender, EventArgs e)
  {
   if(this.tb_KeyValue.Focused)
   {
    this.ListDataGrid.Visible=false;
   }
  }

  private void _ListDataGrid_MyGetFormKeyPress(object sender, KeyPressEventArgs e)
  {
   this.OnKeyPress(e);
  }

 

 }


/// <summary>
 /// 声明一个代表,用于引发窗体失去焦点的事件
 /// </summary>
 public delegate void  SetOutControl(ref Message msg ,System.Windows.Forms.Keys  keyData);

 public delegate void  GetFormKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e);
 
 /// <summary>
 /// 显示浮动列表
 /// </summary>
 public class FrmDataList : Form
 {
  public DataGrid dataGrid1;

  public event SetOutControl mySetControl ;
  public event GetFormKeyPress MyGetFormKeyPress ;
  private System.ComponentModel.IContainer components = null;

  public FrmDataList()
  {
   // 该调用是 Windows 窗体设计器所必需的。
   InitializeComponent();
    
   // TODO: 在 InitializeComponent 调用后添加任何初始化
   
   
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  /// <summary>
  /// 事件处理
  /// </summary>
  /// <param name="msg"></param>
  /// <param name="keyData"></param>
  protected void OnMySetControl(ref Message msg, System.Windows.Forms.Keys  keyData )
  {
   if (this.mySetControl !=null)
   {
    this.mySetControl(ref msg,  keyData);
   }
  }


  protected void OnMyGetFormKeyPress(object sender ,System.Windows.Forms.KeyPressEventArgs e)
  {
   if (this.MyGetFormKeyPress!=null)
   {
    this.MyGetFormKeyPress(sender,e);
   }
  }
  #region 设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.components = new System.ComponentModel.Container();
   System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ComboBoxListFrm));
   this.dataGrid1 = new DataGrid(this.components);
   ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
   this.SuspendLayout();
   //
   // dataGrid1
   //
   this.dataGrid1.AccessibleDescription = resources.GetString("dataGrid1.AccessibleDescription");
   this.dataGrid1.AccessibleName = resources.GetString("dataGrid1.AccessibleName");
   this.dataGrid1.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("dataGrid1.Anchor")));
   this.dataGrid1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("dataGrid1.BackgroundImage")));
   this.dataGrid1.CaptionFont = ((System.Drawing.Font)(resources.GetObject("dataGrid1.CaptionFont")));
   this.dataGrid1.CaptionText = resources.GetString("dataGrid1.CaptionText");
   this.dataGrid1.CaptionVisible = false;
   this.dataGrid1.DataMember = "";
   this.dataGrid1.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("dataGrid1.Dock")));
   this.dataGrid1.Enabled = ((bool)(resources.GetObject("dataGrid1.Enabled")));
   this.dataGrid1.Font = ((System.Drawing.Font)(resources.GetObject("dataGrid1.Font")));
   this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
   this.dataGrid1.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("dataGrid1.ImeMode")));
   this.dataGrid1.Location = ((System.Drawing.Point)(resources.GetObject("dataGrid1.Location")));
   this.dataGrid1.Name = "dataGrid1";
   this.dataGrid1.ReadOnly = true;
   this.dataGrid1.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("dataGrid1.RightToLeft")));
   this.dataGrid1.Size = ((System.Drawing.Size)(resources.GetObject("dataGrid1.Size")));
   this.dataGrid1.TabIndex = ((int)(resources.GetObject("dataGrid1.TabIndex")));
   this.dataGrid1.Visible = ((bool)(resources.GetObject("dataGrid1.Visible")));
   //
   // ComboBoxListFrm
   //
   this.AccessibleDescription = resources.GetString("$this.AccessibleDescription");
   this.AccessibleName = resources.GetString("$this.AccessibleName");
   this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize")));
   this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll")));
   this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin")));
   this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize")));
   this.BackColor = System.Drawing.SystemColors.ControlDark;
   this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
   this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize")));
   this.Controls.Add(this.dataGrid1);
   this.Enabled = ((bool)(resources.GetObject("$this.Enabled")));
   this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font")));
   this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
   this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
   this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode")));
   this.KeyPreview = true;
   this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location")));
   this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize")));
   this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize")));
   this.Name = "ComboBoxListFrm";
   this.Opacity = 0.9;
   this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft")));
   this.ShowInTaskbar = false;
   this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition")));
   this.Text = resources.GetString("$this.Text");
   this.TopMost = true;
   ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// 当用户按非向上,向下,向左,向右键时引发窗体失去焦点的事件.
  /// </summary>
  /// <param name="msg"></param>
  /// <param name="KeyData"></param>
  /// <returns></returns>
   protected override bool ProcessCmdKey(ref Message msg, Keys KeyData)
    {
  
    if  (!(KeyData ==Keys.Down  || KeyData==Keys.Up || KeyData==Keys.Left || KeyData ==Keys.Right) )
    {
     this.OnMySetControl(ref msg,KeyData);
     return true;
    }
    else
    {
     return base.ProcessCmdKey (ref msg, KeyData);
    }
 
 
   }


  protected override void OnKeyPress(KeyPressEventArgs e)
  {
   //e.Handled =true;
   int k =(int)(e.KeyChar);
   if( !( k ==(int)(Keys.Down)  || k==(int)(Keys.Up) || k==(int)(Keys.Left) || k ==(int)(Keys.Right)) )
   {
     this.OnMyGetFormKeyPress(this,e);

   }
   
   base.OnKeyPress (e);
  }

  

 }
}


测试代码:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace TestControls
{
 /// <summary>
 /// Form1 的摘要说明。
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {
  private Controller.FindDataTextBox danWeiComboBox1;
  private System.Windows.Forms.TextBox textBox1;
  private System.Windows.Forms.TextBox textBox2;
  private System.Windows.Forms.ComboBox comboBox1;
  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private System.ComponentModel.Container components = null;

  public Form1()
  {
   //
   // Windows 窗体设计器支持所必需的
   //
   InitializeComponent();

   //
   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
   //
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows 窗体设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.danWeiComboBox1 = new Controller.FindDataTextBox();
   this.textBox1 = new System.Windows.Forms.TextBox();
   this.textBox2 = new System.Windows.Forms.TextBox();
   this.comboBox1 = new System.Windows.Forms.ComboBox();
   this.SuspendLayout();
   //
   // danWeiComboBox1
   //
   this.danWeiComboBox1.DataSource = null;
   this.danWeiComboBox1.DisplayItem = "";
   this.danWeiComboBox1.Location = new System.Drawing.Point(192, 264);
   this.danWeiComboBox1.Name = "danWeiComboBox1";
   this.danWeiComboBox1.Size = new System.Drawing.Size(224, 24);
   this.danWeiComboBox1.TabIndex = 0;
   this.danWeiComboBox1.ValueItem = "";
   //
   // textBox1
   //
   this.textBox1.Location = new System.Drawing.Point(424, 296);
   this.textBox1.Name = "textBox1";
   this.textBox1.Size = new System.Drawing.Size(176, 21);
   this.textBox1.TabIndex = 1;
   this.textBox1.Text = "textBox1";
   //
   // textBox2
   //
   this.textBox2.Location = new System.Drawing.Point(392, 88);
   this.textBox2.Name = "textBox2";
   this.textBox2.Size = new System.Drawing.Size(176, 21);
   this.textBox2.TabIndex = 2;
   this.textBox2.Text = "textBox2";
   //
   // comboBox1
   //
   this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
   this.comboBox1.Location = new System.Drawing.Point(32, 88);
   this.comboBox1.Name = "comboBox1";
   this.comboBox1.Size = new System.Drawing.Size(240, 20);
   this.comboBox1.TabIndex = 3;
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(696, 429);
   this.Controls.Add(this.comboBox1);
   this.Controls.Add(this.textBox2);
   this.Controls.Add(this.textBox1);
   this.Controls.Add(this.danWeiComboBox1);
   this.Name = "Form1";
   this.Text = "Form1";
   this.Load += new System.EventHandler(this.Form1_Load);
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

  private void Form1_Load(object sender, System.EventArgs e)
  {
   System.Data.DataTable dt ;
   System.Data.DataColumn  dc ;
   System.Data.DataRow dr;
   dt =new System.Data.DataTable();
   dc =new System.Data.DataColumn("机构名称");
   dt.Columns.Add(dc);
   dc =new System.Data.DataColumn("机构代码");
   dt.Columns.Add(dc);
   dr =dt.NewRow();
   dr[0]="无为县中医院";
   dr[1]="1001";

   dt.Rows.Add(dr);
   dr =dt.NewRow();
   dr[0]="无为县人民医院";
   dr[1]="1002";
   dt.Rows.Add(dr);

   dr=dt.NewRow();
   dr[0]="安徽医科大学第一附属医院";
   dr[1]="2001";
            dt.Rows.Add(dr);

   dr=dt.NewRow();
   dr[0]="安徽省立医院";
   dr[1]="2002";
   dt.Rows.Add(dr);

   dr=dt.NewRow();
   dr[0]="安徽省立儿童医院";
   dr[1]="2003";
   dt.Rows.Add(dr);


   dr=dt.NewRow();
   dr[0]="北京医科大学第一附属医院";
   dr[1]="3001";
   dt.Rows.Add(dr);

   dr=dt.NewRow();
   dr[0]="北京中医院";
   dr[1]="3002";
   dt.Rows.Add(dr);

   dr=dt.NewRow();
   dr[0]="北京儿童医院";
   dr[1]="3003";
   dt.Rows.Add(dr);

   this.danWeiComboBox1.DataSource=dt;
   this.danWeiComboBox1.RowFilterExpression="机构代码 like '{0}*' or 机构名称 like '{0}*' "; 
   this.danWeiComboBox1.SortColumnName="机构代码";
   this.danWeiComboBox1.DisplayItem="机构名称" ;
   this.danWeiComboBox1.ValueItem="机构代码" ;


  }
 }
}


待解决问题:

当DataGrid获得焦点时,如何让在datagrid上的按键消息传递给TextBox控件.