文本框自动完成(多行)

gre*_*ics 11 c# autocomplete winforms

我在C#中制作了一个自动建议/完整文本框,我按照下面的链接,但文本框没有显示建议

如何在Windows窗体中创建自动提示文本框?

//-------- Get all distinct description -----------------------------
OleDbCommand command = new OleDbCommand(Queries.qry16, Connection);
OleDbDataReader reader = command.ExecuteReader();

//--------- Storing ------------------------------------
while (reader.Read())
{
    namesCollection.Add(reader.GetValue(0).ToString());
}

//----------- Close after use ---------------------------------------
reader.Close();

//----------- Set the auto suggestion in description box ------------
descriptionBox.AutoCompleteMode = AutoCompleteMode.Suggest;
descriptionBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
descriptionBox.AutoCompleteCustomSource = namesCollection;
Run Code Online (Sandbox Code Playgroud)

这是我的代码,它是winform的加载函数.并且nameCollection初始化在构造函数中...请帮助使其正常工作.

我正在编辑我的帖子而不是创建新的...我已经在单行文本框中尝试了我自己的代码并且它有效.现在我想在多行中使用相同的...对于研究我用Google搜索超过2天尝试不同的代码(一个具有智能感)但它没有在文本框中提供自动建议.任何人都可以给我建议将整个程序编码为多行..谢谢.

hel*_*dre 11

AutoCompleteSource不适用于多行TextBox控件.

这意味着你需要从头开始:

我会创建一个ListBox来显示自动完成的内容:

var listBox = new ListBox();
Controls.Add(listBox);
Run Code Online (Sandbox Code Playgroud)

你需要对你的文本框进行事件处理,但这有点粗糙,所以我会重写它以在某些时候停止keyupevent:

private void textBox_KeyUp(object sender, KeyEventArgs e)
{
    var x = textBox.Left;
    var y = textBox.Top + textBox.Height;
    var width = textBox.Width + 20;
    const int height = 40;

    listBox.SetBounds(x, y, width, height );
    listBox.KeyDown += listBox_SelectedIndexChanged;

    List<string> localList = list.Where(z => z.StartsWith(textBox.Text)).ToList();
    if(localList.Any() && !string.IsNullOrEmpty(textBox.Text))
    {
        listBox.DataSource = localList;
        listBox.Show();
        listBox.Focus();

    }
}
Run Code Online (Sandbox Code Playgroud)

现在您只需要一个处理程序来设置textBox中的文本:

 void listBox_SelectedIndexChanged(object sender, KeyEventArgs e)
    {
        if(e.KeyValue == (decimal) Keys.Enter)
        {
            textBox2.Text = ((ListBox)sender).SelectedItem.ToString();
            listBox.Hide();                
        }
    }
Run Code Online (Sandbox Code Playgroud)

在适当的地方进行空检查