AutoComplete TextBox Control

前端 未结 9 1294
误落风尘
误落风尘 2020-11-27 04:48

I want to have a textbox control that suggests and append values from a database in a Windows application with C# 2008 and LINQ.

I do it with a combobox but I can\'t

9条回答
  •  天命终不由人
    2020-11-27 05:28

    of course it depends on how you implement it but perhaps this is a good start:

    using System.Windows.Forms;
    
    public class AutoCompleteTextBox : TextBox {
    
        private string[] database;//put here the strings of the candidates of autocomplete
        private bool changingText = false;
    
        protected override void OnTextChanged (EventArgs e) {
            if(!changingText && database != null) {
                //searching the first candidate
                string typed = this.Text.Substring(0,this.SelectionStart);
                string candidate = null;
                for(int i = 0; i < database.Length; i++)
                    if(database[i].Substring(0,this.SelectionStart) == typed) {
                        candidate = database[i].Substring(this.SelectionStart,database[i].Length);
                        break;
                    }
                if(candidate != null) {
                    changingText = true;
                    this.Text = typed+candidate;
                    this.SelectionStart = typed.Length;
                    this.SelectionLength = candidate.Length;
                }
            }
            else if(changingText)
                changingText = false;
            base.OnTextChanged(e);
        }
    
    }
    

    I'm not sure this is working very well, but I think the base of this code is good enough.

提交回复
热议问题