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; } } }
收工
时间: 2024-10-12 16:39:55