我有一个简单的表单,里面有一个文本框,我正在尝试制作一个用户友好的自动建议文本框..
根据当前场景,我正在使用AutoCompleteStringCollection
类,通过该类,我可以使文本框显示以在文本框中输入的特定文本开头的单词的建议。但是,我想让我的程序即使在某个部分也应该显示建议来自数据库的字符串与 Textbox.Text 匹配。
目前,我可以使用 . 根据 userInput 过滤来自 DB 的数据dataView
。但我仍然无法在前端显示输出。
我已经尝试了所有文本框事件,例如 ' KeyPress
', KeyDown
, KeyUp
,TextChanged
但它不起作用....
我的代码::
public partial class Form2 : Form
{
AutoCompleteStringCollection autoCompletefromDB = new AutoCompleteStringCollection();
AutoCompleteStringCollection searchResults = new AutoCompleteStringCollection();
MyLinqDataContext dtcontext = new MyLinqDataContext();
// static string searchChar = "";
SqlConnection con = new SqlConnection("Data Source=DATASERVER\\SQL2K8;Initial Catalog=VTMMedicalContent;Persist Security Info=True;User ID=vtm;Password=M3d!c@l");
DataTable dTable = new DataTable();
SqlCommand cmd;
SqlDataAdapter da;
DataView dtView;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select DiagnosisName from [VTMMedicalContent].[dbo].[DiagnosisMaster]";
da = new SqlDataAdapter(cmd);
da.Fill(dTable);
dtView = new DataView(dTable);
}
//And My KeyPress Event Code..
private void txtAutoComplete_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsControl(e.KeyChar))
{
dtView.RowFilter = dtView.Table.Columns[0].ColumnName + " Like '%" + e.KeyChar + "%'";
foreach (DataRowView dtViewRow in dtView)
searchResults.Add(dtViewRow[0].ToString());
txtAutoComplete.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtAutoComplete.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtAutoComplete.AutoCompleteCustomSource = searchResults;
}
//MessageBox.Show("The Elements in searchResult are:" + searchResults.Count);
}
我尝试在KeyDown
, KeyUp
,TextChanged
事件中编写相同的代码,但没有用..:(
它仅适用于 Form_Load 但仅显示与单词起点匹配的建议..