Eth*_*son 5 c# autocomplete winforms
什么是开发文本框的最佳方法,该文本框记住放入其中的最后x个条目.这是一个用C#编写的独立应用程序.
这实际上相当容易,特别是在显示"自动完成"部分方面.在记住最后x个条目时,您只需要决定您认为是完成的条目的特定事件(或事件),并将该条目写入列表... AutoCompleteStringCollection将是精确.
TextBox类具有以下3个属性,您将需要它们:
将AutoCompleteMode设置为SuggestAppend,将AutoCompleteSource设置为CustomSource.
然后在运行时,每次创建一个新条目时,使用AutoCompleteStringCollection的Add()方法将该条目添加到列表中(如果需要,弹出任何旧条目).实际上,您可以直接在TextBox的AutoCompleteCustomSource属性上执行此操作,只要您已经初始化它.
现在,每次输入TextBox时都会建议以前的条目:)
有关更完整的示例,请参阅此文章:http://www.c-sharpcorner.com/UploadFile/mahesh/AutoCompletion02012006113508AM/AutoCompletion.aspx
AutoComplete还有一些内置的功能,如FileSystem和URL(尽管它只会输入输入到IE中的内容......)
我忘记了您想要保存它的事实,因此这不是每个会话唯一的事情:P但是,是的,您是完全正确的。
这很容易完成,特别是因为它只是基本字符串,只需将 AutoCompleteCustomSource 的内容从 TextBox 写到文本文件中,在单独的行上即可。
我有几分钟的时间,所以我写了一个完整的代码示例...我以前会这样做,因为我总是尝试展示代码,但没有时间。不管怎样,这就是全部内容(减去设计器代码)。
namespace AutoComplete
{
public partial class Main : Form
{
//so you don't have to address "txtMain.AutoCompleteCustomSource" every time
AutoCompleteStringCollection acsc;
public Main()
{
InitializeComponent();
//Set to use a Custom source
txtMain.AutoCompleteSource = AutoCompleteSource.CustomSource;
//Set to show drop down *and* append current suggestion to end
txtMain.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
//Init string collection.
acsc = new AutoCompleteStringCollection();
//Set txtMain's AutoComplete Source to acsc
txtMain.AutoCompleteCustomSource = acsc;
}
private void txtMain_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Only keep 10 AutoComplete strings
if (acsc.Count < 10)
{
//Add to collection
acsc.Add(txtMain.Text);
}
else
{
//remove oldest
acsc.RemoveAt(0);
//Add to collection
acsc.Add(txtMain.Text);
}
}
}
private void Main_FormClosed(object sender, FormClosedEventArgs e)
{
//open stream to AutoComplete save file
StreamWriter sw = new StreamWriter("AutoComplete.acs");
//Write AutoCompleteStringCollection to stream
foreach (string s in acsc)
sw.WriteLine(s);
//Flush to file
sw.Flush();
//Clean up
sw.Close();
sw.Dispose();
}
private void Main_Load(object sender, EventArgs e)
{
//open stream to AutoComplete save file
StreamReader sr = new StreamReader("AutoComplete.acs");
//initial read
string line = sr.ReadLine();
//loop until end
while (line != null)
{
//add to AutoCompleteStringCollection
acsc.Add(line);
//read again
line = sr.ReadLine();
}
//Clean up
sr.Close();
sr.Dispose();
}
}
}
Run Code Online (Sandbox Code Playgroud)
该代码将完全按原样工作,您只需使用名为 txtMain 的 TextBox 创建 GUI,并将 KeyDown、Closed 和 Load 事件连接到 TextBox 和主窗体。
另请注意,对于此示例并为了简单起见,我只是选择检测按下的 Enter 键作为触发器以将字符串保存到集合中。根据您的需要,可能有更多/不同的活动会更好。
此外,用于填充集合的模型也不是很“智能”。当集合达到 10 的限制时,它只是删除最旧的字符串。这可能并不理想,但适用于该示例。您可能需要某种评级系统(特别是如果您真的希望它像 Google 那样)
最后一点,建议实际上会按照它们在集合中的顺序显示。如果出于某种原因您希望它们以不同的方式显示,只需按您喜欢的方式对列表进行排序即可。
希望有帮助!