用combobox控件来显示用户
Dictionary<string, UserInfo> users = new Dictionary<string, UserInfo>();
public void SavePW()//保存用户和密码
{
UserInfo user = new UserInfo();
// 登录时 如果没有Data.bin文件就创建、有就打开
FileStream fs = new FileStream("data.bin", FileMode.OpenOrCreate);
BinaryFormatter bf = new BinaryFormatter();
// 保存在实体类属性中
user.LoginID = txtUser.Text.Trim();
//保存密码选中状态
if (checkBoxXpw.Checked)
user.Pwd = txtPwd.Text.Trim();
else
user.Pwd = "";
//选在集合中是否存在用户名
if (users.ContainsKey(user.LoginID))
{
//如果有清掉
users.Remove(user.LoginID);
}
//添加用户信息到集合
users.Add(user.LoginID, user);
//写入文件
bf.Serialize(fs, users);
//关闭
fs.Close();
}
public void OpenPW()//打开用户和密码
{
FileStream fs = new FileStream("data.bin", FileMode.OpenOrCreate);
//fs.Seek(0, SeekOrigin.Begin);
if (fs.Length > 0)
{
BinaryFormatter bf = new BinaryFormatter();
fs.Position = 0;
//读出存在Data.bin 里的用户信息
users = bf.Deserialize(fs) as Dictionary<string, UserInfo>;
//循环添加到Combox1
foreach (UserInfo user in users.Values)
{
txtUser.Items.Add(user.LoginID);
}
//combox1 用户名默认选中第一个
//if (txtUser.Items.Count > 0)
// txtUser.SelectedIndex = txtUser.Items.Count - 1;
}
fs.Close();
}
private void txtUser_SelectedValueChanged(object sender, EventArgs e)
{
FileStream fs = new FileStream("data.bin", FileMode.OpenOrCreate);
if (fs.Length > 0)
{
BinaryFormatter bf = new BinaryFormatter();
users = bf.Deserialize(fs) as Dictionary<string, UserInfo>;
for (int i = 0; i < users.Count; i++)
{
if (txtUser.Text != "")
{
if (users.ContainsKey(txtUser.Text) && users[txtUser.Text].Pwd != "")
{
txtPwd.Text = users[txtUser.Text].Pwd;
checkBoxXpw.Checked = true;
}
else
{
txtPwd.Text = "";
checkBoxXpw.Checked = false;
}
}
}
}
fs.Close();
}
}
[Serializable]
public class UserInfo
{
public string LoginID
{
get;
set;
}
public string Pwd
{
get;
set ;
}
}