日期:2014-05-19  浏览次数:21211 次

WinForm下用TextBox保存密码的问题??
我在VS.NET2005环境下用C#编程,现在想实现用TextBox保存用户名及密码的功能,就像许多网站上的那样,可是找不到类似的属性和方法。
哪位高手能指点一下呀?
谢谢了!!

------解决方案--------------------
属性 AutoCompleteCustomSource,AutoCompleteMode,AutoCompleteSource 用于自动完成功能...

使用 AutoCompleteCustomSource、AutoCompleteMode 和 AutoCompleteSource 属性创建一个 TextBox,它可将所输入的字符串前缀与所维护源中的所有字符串的前缀进行比较来自动完成输入字符串的填写。这对于将 URL、地址、文件名或命令频繁输入其中的 TextBox 控件来说很有用。

AutoCompleteCustomSource 属性的使用是可选的,但必须将 AutoCompleteSource 属性设置为 CustomSource 后才能使用 AutoCompleteCustomSource。

AutoCompleteMode 和 AutoCompleteSource 属性必须一起使用。

注意
操作系统可能会限制可以同时显示的自定义字符串的数目。
------解决方案--------------------
首先楼主肯定要把原先使用过的用户名和密码按照一定格式保存下来,否则Windows才不会帮你存呢。然后使用Textbox的AutoComplete功能(.NET 2.0才有)就能实现,源代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace AutoComplete
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private string accountFilePath =
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\accounts.dat ";

private IDictionary <string, string> accounts = new SortedList <string, string> ();

private void Form1_Load(object sender, EventArgs e)
{
ReloadAccounts();
}

private void SaveButton_Click(object sender, EventArgs e)
{
if (accounts.ContainsKey(UsernameTextBox.Text))
{
accounts[UsernameTextBox.Text] = PasswordTextBox.Text;
}
else
{
accounts.Add(UsernameTextBox.Text, PasswordTextBox.Text);
}

using (StreamWriter writer = new StreamWriter(accountFilePath))
{
foreach (KeyValuePair <string, string> account in accounts)
{
writer.WriteLine(account.Key);
writer.WriteLine(account.Value);
}
}

ReloadAccounts();
}

private void ReloadAccounts()
{
UsernameTextBox.AutoCompleteCustomSource.Clear();
accounts.Clear();
if (!File.Exists(accountFilePath))
{
return;
}
using (StreamReader reader = new StreamReader(accountFilePath))
{
while (true)
{
string username = reader.ReadLine();
if (string.IsNullOrEmpty(username)) break;
string password = reader.ReadLine();
if (string.IsNullOrEmpty(password)) break;
accounts.Add(username, password);
UsernameTextBox.AutoCompleteCustomSource.Add(username);
}
}
}

private void UsernameTextBox_Leave(object sender, EventArgs e)
{
string password = string.Empty;
if (accounts.TryGetValue(UsernameTextBox.Text, out password))
PasswordTextBox.Text = password;
}
}
}