2014-10-28 87 views
0

IDE:Visual Studio,Winforms,C#.net 4.0为什么自动完成建议没有在文本框中更新

我正在创建一个具有建议功能的文本框。问题在于它给出的建议与首字母为例如。假设源包含'你好用户,当用户将输入“用户”它不会给任何建议, 为了处理这种情况我已经写了下面的代码:

private void Type2_Load(object sender, EventArgs e) 
{    
    source = new List<string>(); 
    source.Add("aaaaaa"); 
    source.Add("bbbbbb"); 
    source.Add("cccccc"); 
    source.Add("aa"); 
    source.Add("yogesshaaa"); 
    source.Add("yogesh aaa"); 

    BindTextBox(source);  
} 

private void BindTextBox(List<string> bindWith) 
{ 
    // txt.Invalidate(); 
    ss = new AutoCompleteStringCollection(); 

    txt.AutoCompleteCustomSource = null; 
    txt.AutoCompleteMode = AutoCompleteMode.None; 
    txt.AutoCompleteSource = AutoCompleteSource.None; 
    // ss.AddRange(bindWith.ToArray()); 

    txt.AutoCompleteCustomSource = ss; 
    txt.AutoCompleteMode = AutoCompleteMode.Suggest; 
    txt.AutoCompleteSource = AutoCompleteSource.CustomSource; 
    ss.AddRange(bindWith.ToArray()); 
} 

private void txt_TextChanged(object sender, EventArgs e) 
{ 
    List<string> lstNewList = new List<string>(); 
    foreach (string s in source) 
    { 
     if(s.Contains(txt.Text)) 
     { 
      lstNewList.Add(s); 
     } 
    } 

    BindTextBox(lstNewList); 
} 

在这里,在txt_TextChanged事件我创建一个newList其中包含在txtBox建议中建议的单词,我正在重新绑定该文本框,但它没有给我提供更新的建议。 请告诉我如何解决这种情况。

+0

你没有添加任何东西到列表中,你只是循环通过当前的源代码并添加回来。也许你的意思是如果(!s.Contains(txt.Text)) – Sorceri 2014-10-28 13:32:19

回答

0

我对自动填充的解决方案:

首先你要调用你的文本框ControlAdded事件:

private void tb_ControlAdded(object sender, ControlEventArgs e) 
    { 

     TextBox autoText = e.Control as TextBox; 
     if (autoText != null) 
     { 
      autoText.AutoCompleteMode = AutoCompleteMode.Suggest; 
      autoText.AutoCompleteSource = AutoCompleteSource.CustomSource; 
      AutoCompleteStringCollection DataCollection = new AutoCompleteStringCollection(); 
      addItems(DataCollection); 
      autoText.AutoCompleteCustomSource = DataCollection; 
     } 
    } 

则创造了“为addItems”的方法如下:

public void addItems(AutoCompleteStringCollection col) 
      { 
       col.Add("Value 1"); 
       col.Add("Value 2"); 
      } 

我希望这能解决您的问题...祝您有个美好的一天!