winform combobox控制項綁定datatable並實現實現模糊查詢,顯示下拉列表,網上太多案例,都不是我所需要的,研究了一下 不用Dev 也能實現不錯的效果。 廢話不多直接代碼加圖片 先看效果圖 NO1. combobox 綁定數據源 NO2.ComboBox添加TextUpdate事件 ...
winform combobox控制項綁定datatable並實現實現模糊查詢,顯示下拉列表,網上太多案例,都不是我所需要的,研究了一下 不用Dev 也能實現不錯的效果。
廢話不多直接代碼加圖片
先看效果圖
NO1. combobox 綁定數據源
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; } } }
收工