winform combobox控件綁定datatable並實現實現模糊查詢,顯示下拉列表,網上太多案例,都不是我所須要的,研究了一下 不用Dev 也能實現不錯的效果。指針
廢話很少直接代碼加圖片code
先看效果圖orm
NO1. combobox 綁定數據源blog
private void BindPaperCodeA() { //綁定數據時 刪除 SelectedIndexChanged cmbPaperCode.SelectedIndexChanged -= new EventHandler(cmbPaperCode_SelectedIndexChanged); cmbPaperCode.ValueMember = "id"; cmbPaperCode.DisplayMember = "call"; DataTable dt = pagerModelBLL.GetList(" state=" + ((int)EState.Normal).ToString() + " and paper_code=" + cmbPaperType.SelectedValue.ToString()).Tables[0]; DataRow dr = dt.NewRow(); dr["id"] = "0"; dr["call"] = "所有"; dt.Rows.InsertAt(dr, 0); cmbPaperCode.DataSource = dt; //綁定數據完成時 綁定SelectedIndexChanged事件 cmbPaperCode.SelectedIndexChanged += new EventHandler(cmbPaperCode_SelectedIndexChanged); }
NO2.ComboBox添加TextUpdate事件事件
private void cmbPaperCode_TextUpdate(object sender, EventArgs e) { cmbPaperCode.ValueMember = "id"; cmbPaperCode.DisplayMember = "call"; DataTable dt = pagerModelBLL.GetList(" state=" + ((int)EState.Normal).ToString() + " and paper_code=" + cmbPaperType.SelectedValue.ToString()).Tables[0]; DataRow dr = dt.NewRow();dr["id"] = "0";dr["call"] = "所有";dt.Rows.InsertAt(dr, 0); if (string.IsNullOrEmpty(cmbPaperCode.Text.Trim())) { cmbPaperCode.DataSource = dt; } else { DataTable dt2 = pagerModelBLL.GetList(" state=" + ((int)EState.Normal).ToString() + " and call like '" + cmbPaperCode.Text.Trim() + "%' and paper_code=" + cmbPaperType.SelectedValue.ToString()).Tables[0]; if (dt2 != null && dt2.Rows.Count > 0) { DataRow[] drS = dt2.Select(" call= '" + cmbPaperCode.Text + "'"); if (drS.Length > 0) { cmbPaperCode.DataSource = dt2; cmbPaperCode.SelectedValue = drS[0]["id"].ToString(); } else { DataRow dr2 = dt2.NewRow(); dr2["id"] = "0"; dr2["call"] = cmbPaperCode.Text; dt2.Rows.InsertAt(dr2, 0); cmbPaperCode.DataSource = dt2;
//保持鼠標指針原來狀態,有時候鼠標指針會被下拉框覆蓋,因此要進行一次設置。 Cursor = Cursors.Default; //自動彈出下拉框 cmbPaperCode.DroppedDown = true; cmbPaperCode.SelectionLength = 0; //設置光標位置,不然光標位置始終保持在第一列,形成輸入關鍵詞的倒序排列 cmbPaperCode.SelectionStart = cmbPaperCode.Text.Length; } } else { cmbPaperCode.DataSource = dt; } } }
收工圖片
個人小站get