2014-10-28 27 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"); 
      } 

我希望這能解決您的問題...祝您有個美好的一天!