为控件增加自动完成功能[转]
很多朋友说,选择了自动完成后,关闭程序,再次打开还是会消失,只在程序执行时会有。在这里我要告诉大家,不仅要选择AutoCompleteCustomSource属性,还需要写代码,或选择项目的属性设置才可以。
下面我把一些过程详细的和大家说一下。
1.选择AutoCompleteMode为Suggest,选择AutoCompleteSource为AutoCompleteCustomSource.

2.配置项目的属性设置,自定义自己的键名,我定义的为"HistoryKey"
private void toolStripButton3_Click(object sender, EventArgs e)
{
if (CanHistoryKey == true) //让用户自己设置是否愿意使用自动完成的功能
{
AutoCompleteStringCollection auto = new AutoCompleteStringCollection();//定义并实例化AutoCompleteStringCollection类
if (MyLib.Properties.Settings.Default.HistoryKey != null)
auto = MyLib.Properties.Settings.Default.HistoryKey;//设置时HistoryKey的值是为null的,所以不为空时我们需要加载旧的历史关键字
auto.Add(toolStripTextBox1.Text.Trim()); //添加新的历史关键字
MyLib.Properties.Settings.Default.HistoryKey = auto; //将历史关键字进行更新(不过并没有保存)
toolStripTextBox1.AutoCompleteCustomSource = auto; //立刻为控件添加新的历史关键字
}
}
在Form1_Load中加入
toolStripTextBox1.AutoCompleteCustomSource = MyLib.Properties.Settings.Default.HistoryKey;
最重要的是要在关闭窗口前保存这些记录,要不然你关闭程序后,下次再执行时还是没有以前的记录了。
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
MyLib.Properties.Settings.Default.Save();
}
最后还要有一个清除的功能
private void 清空历史记录ToolStripMenuItem_Click(object sender, EventArgs e)
{
MyLib.Properties.Settings.Default.HistoryKey = null;
toolStripTextBox1.AutoCompleteCustomSource = null;
}
(我发现清除时,直接使用MyLib.Properties.Settings.Default.HistoryKey = null;就可以了,而且不用使用MyLib.Properties.Settings.Default.HistoryKey.Save();也可以。)
好啦,最后看看效果吧,很不错的哦。至此我们为露雨资源库又添加了一个贴心的小功能。 :)
下面我把一些过程详细的和大家说一下。
1.选择AutoCompleteMode为Suggest,选择AutoCompleteSource为AutoCompleteCustomSource.
2.配置项目的属性设置,自定义自己的键名,我定义的为"HistoryKey"

private void toolStripButton3_Click(object sender, EventArgs e)
{
if (CanHistoryKey == true) //让用户自己设置是否愿意使用自动完成的功能
{
AutoCompleteStringCollection auto = new AutoCompleteStringCollection();//定义并实例化AutoCompleteStringCollection类
if (MyLib.Properties.Settings.Default.HistoryKey != null)
auto = MyLib.Properties.Settings.Default.HistoryKey;//设置时HistoryKey的值是为null的,所以不为空时我们需要加载旧的历史关键字
auto.Add(toolStripTextBox1.Text.Trim()); //添加新的历史关键字
MyLib.Properties.Settings.Default.HistoryKey = auto; //将历史关键字进行更新(不过并没有保存)
toolStripTextBox1.AutoCompleteCustomSource = auto; //立刻为控件添加新的历史关键字
}
}在Form1_Load中加入
toolStripTextBox1.AutoCompleteCustomSource = MyLib.Properties.Settings.Default.HistoryKey; 
最重要的是要在关闭窗口前保存这些记录,要不然你关闭程序后,下次再执行时还是没有以前的记录了。
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
MyLib.Properties.Settings.Default.Save();
}最后还要有一个清除的功能
private void 清空历史记录ToolStripMenuItem_Click(object sender, EventArgs e)
{
MyLib.Properties.Settings.Default.HistoryKey = null;
toolStripTextBox1.AutoCompleteCustomSource = null;
}(我发现清除时,直接使用MyLib.Properties.Settings.Default.HistoryKey = null;就可以了,而且不用使用MyLib.Properties.Settings.Default.HistoryKey.Save();也可以。)
好啦,最后看看效果吧,很不错的哦。至此我们为露雨资源库又添加了一个贴心的小功能。 :)



浙公网安备 33010602011771号