本文介绍了winform-基于键入的历史记录的自动完成文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尊敬的专家,
我想在winform中为文本框实现自动完成功能,就像SAP一样,SAP将基于用户输入而不是外部文件/数据库或硬编码集合.
谢谢,
--- Anil Kumar
Dear Experts,
I want to implement autocomplete feature in my winform for textbox just like SAP which will be based on user input instead of external file/database or hard-coded collections.
Thanks,
--- Anil Kumar
推荐答案
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace AutoComplete
{
static class Program
{
[STAThread] // You have to set STA when using AutoCompleteCustomSource !!!!
static void Main()
{
// Create a Form
Form form = new Form();
// ... and a description Label
Label label = new Label();
label.Text = "I will remember";
label.Dock = DockStyle.Top;
// Now create a TexBox
TextBox textbox = new TextBox();
textbox.Dock = DockStyle.Top;
// ... and enable AutoComplete
textbox.AutoCompleteMode = AutoCompleteMode.SuggestAppend; // Set the AutoCompleteMode you like
textbox.AutoCompleteSource = AutoCompleteSource.CustomSource; // we will use a custome source (the entered text)
// create a button to simulate validate/lost focus (whatever your real strategy will be)
Button button = new Button();
button.Dock = DockStyle.Top;
button.Text = "Add to history";
// if the button is clicked the text should be added to history
button.Click += delegate(object sender, EventArgs e)
{
// add a new text to the AutoCompleteCustomSource list
string strTextToAdd = textbox.Text;
if (!String.IsNullOrWhiteSpace(strTextToAdd))// in reality you will want filter or validate the text
{
textbox.AutoCompleteCustomSource.Add(strTextToAdd);
}
// lets clear the textbox after that in this example
textbox.Text = String.Empty;
// ... and refocus it
textbox.Focus();
};
// Add all the Controls to the Form
form.Controls.Add(button);
form.Controls.Add(textbox);
form.Controls.Add(label);
// ... and show the form
Application.Run(form);
}
}
}
这篇关于winform-基于键入的历史记录的自动完成文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!