keywords: 拼音 首字母 过滤
在combobox中输入汉字拼音的首字母时,下面列出对应的可选项,就像下面这样
1。 首先在数据库中需要设计一个表,专门用来存放药物及对应的拼音首字母,这样当用户输入拼音字母后就可以到表中查找匹配的药物,然后再显示
2。 下面的委托方法负责将从数据库获得的查询结果集重新邦定到combobox并自动弹出下拉列表。下面的代码需要注意这几行
// set the cursor at the end of the text
ctrl.Focus();
ctrl.Select(oldText.Length, oldText.Length);
其功能就是保证用户能够连续输入字母,并使光标始终位于combobox最后,如果不加这两行,光标就会跑到第一个字母前面
public static void BindDataSource(ComboBox ctrl, DataSet ds)
{
try
{
ctrl.BeginUpdate();
// make sure change it to false, or there will be exception if the droppedDownList is empty
ctrl.DroppedDown = false;
string oldText = ctrl.Text;
ctrl.DataSource = ds.Tables[0];
ctrl.DisplayMember = ds.Tables[0].Columns[0].ColumnName;
// set the text, so user can input continuely
ctrl.Text = oldText;
// set the cursor at the end of the text
ctrl.Focus();
ctrl.Select(oldText.Length, oldText.Length);
// do not drop down if it is empty, or there will be exception
if (ctrl.Items.Count > 0)
{
ctrl.DroppedDown = true;
}
ctrl.Cursor = Cursors.Default;
}
catch (Exception ex)
{
//statusLabel.Text = ex.Message;
}
finally
{
ctrl.EndUpdate();
}
}
3。 下面的方法
// 从数据库中查寻符合条件的药物集合
DataSet ds = mPresenter.GetMedicineNamesByAbbr(abbr);
// 重新邦定
cbM1.BeginInvoke(new ReBindDataSource(BindDataSource), cbM1, ds);
}