本来文章到这里似乎都可以结束了,但是在最后又萌生了一个念头,为了更提高软件的交互性和人性化,我在这里继续添加一个软件记忆功能。
实现的效果图,大致如下:
其实使用软件功能主要要用到textbox的三个属性AutoCompleteCustomSource、AutoCompleteSource、AutoCompleteMode,具体相关属性可参阅MSDN文档:http://msdn.microsoft.com/zh-cn/vstudio/system.windows.forms.textbox.autocompletesource.aspx
OK,设置 txtName的AutoCompleteMode属性为SuggestAppend
AutoCompleteSource属性为CustomSource
给代码做两个地方的修改
一个是(主要是读历史记录)
if
(reg.IsMatch(
this
.txtName.Text))
{
e.Handled = false ;
if (File.Exists( @" c:\1.txt " )) // 路径和文件类型大家自己设置
{
StreamReader sr = new StreamReader( @" c:\1.txt " , true );
string str = sr.ReadLine();
while (str != null ) // 判断不为空行
{
if ( ! this .txtName.AutoCompleteCustomSource.Contains(str)) // 是否包含集合里
{
this .txtName.AutoCompleteCustomSource.Add(str); // 不包含添加
}
str = sr.ReadLine();
}
sr.Close();
}
}
{
e.Handled = false ;
if (File.Exists( @" c:\1.txt " )) // 路径和文件类型大家自己设置
{
StreamReader sr = new StreamReader( @" c:\1.txt " , true );
string str = sr.ReadLine();
while (str != null ) // 判断不为空行
{
if ( ! this .txtName.AutoCompleteCustomSource.Contains(str)) // 是否包含集合里
{
this .txtName.AutoCompleteCustomSource.Add(str); // 不包含添加
}
str = sr.ReadLine();
}
sr.Close();
}
}
另外一处(存入历史记录)
if
(Reader.HasRows)
//
判断是否有查询到对象的数据
{
if (File.Exists( @" c:\1.txt " )) // 判断文件存在
{
if ( ! this .txtName.AutoCompleteCustomSource.Contains( this .txtName.Text)) // 判断记录是否存在
{
StreamWriter sw = new StreamWriter( @" c:\1.txt " , true ); // true参数不可少,否则会覆盖以前存入的记录
sw.WriteLine( this .txtName.Text.Trim()); // 存入记录
sw.Close(); // 关闭文件流
if ( ! this .txtName.AutoCompleteCustomSource.Contains( this .txtName.Text))
{
this .txtName.AutoCompleteCustomSource.Add( this .txtName.Text);
}
}
}
this .DialogResult = DialogResult.OK;
}
{
if (File.Exists( @" c:\1.txt " )) // 判断文件存在
{
if ( ! this .txtName.AutoCompleteCustomSource.Contains( this .txtName.Text)) // 判断记录是否存在
{
StreamWriter sw = new StreamWriter( @" c:\1.txt " , true ); // true参数不可少,否则会覆盖以前存入的记录
sw.WriteLine( this .txtName.Text.Trim()); // 存入记录
sw.Close(); // 关闭文件流
if ( ! this .txtName.AutoCompleteCustomSource.Contains( this .txtName.Text))
{
this .txtName.AutoCompleteCustomSource.Add( this .txtName.Text);
}
}
}
this .DialogResult = DialogResult.OK;
}
为了方便以后使用,你完全可以写成自己的控件,具体方法略~