keywords: 拼音 首字母 过滤
在combobox中输入汉字拼音的首字母时,下面列出对应的可选项,就像下面这样

1。 首先在数据库中需要设计一个表,专门用来存放药物及对应的拼音首字母,这样当用户输入拼音字母后就可以到表中查找匹配的药物,然后再显示
2。 下面的委托方法负责将从数据库获得的查询结果集重新邦定到combobox并自动弹出下拉列表。下面的代码需要注意这几行
// set the cursor at the end of the text
ctrl.Focus();
ctrl.Select(oldText.Length, oldText.Length);
其功能就是保证用户能够连续输入字母,并使光标始终位于combobox最后,如果不加这两行,光标就会跑到第一个字母前面
- public delegate void ReBindDataSource(ComboBox ctrl, DataSet ds);
-
- public static void BindDataSource(ComboBox ctrl, DataSet ds)
- {
- try
- {
- ctrl.BeginUpdate();
-
-
- ctrl.DroppedDown = false;
-
- string oldText = ctrl.Text;
-
- ctrl.DataSource = ds.Tables[0];
- ctrl.DisplayMember = ds.Tables[0].Columns[0].ColumnName;
-
-
- ctrl.Text = oldText;
-
-
- ctrl.Focus();
- ctrl.Select(oldText.Length, oldText.Length);
-
-
- if (ctrl.Items.Count > 0)
- {
- ctrl.DroppedDown = true;
- }
-
- ctrl.Cursor = Cursors.Default;
- }
- catch (Exception ex)
- {
-
- }
- finally
- {
- ctrl.EndUpdate();
- }
-
- }
3。 下面的方法
- private void cbM1_TextUpdate(object sender, EventArgs e)
- {
-
- string abbr = cbM1.Text.Trim();
-
-
- DataSet ds = mPresenter.GetMedicineNamesByAbbr(abbr);
-
- cbM1.BeginInvoke(new ReBindDataSource(BindDataSource), cbM1, ds);
- }