平時在開發中經常會用到用戶登錄這麼個需求,用戶名輸入框我們一般都用TextBox控件。
現在我們需要按照設置好的數量來保存最近登錄過的用戶名,大概的思路就是用一個xml文件來保存最近登錄過的用戶名
首先我們應該將用戶名輸入框改用 ComboBox控件,這樣就可以列出xml文件中已經保存的用戶名了。
下面是運行界面:
接下來是代碼貼圖:
下面貼出代碼:
private string xmlPath = @"d:\\\\user.xml";
private void button1_Click(object sender, EventArgs e)
{
//將用戶名寫入xml
//讀取之前登錄的用戶文件
List<string> list = ReadXmlFile();/<string>
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(dec);
//將當前登錄的用戶名寫入XML文件
XmlElement UserList = doc.CreateElement("User");
doc.AppendChild(UserList);
//如果這個用戶沒有登錄過則添加進XML文件
if (list.Contains(comboBox1.Text.Trim()))
{
XmlElement pName = doc.CreateElement("UserName");
pName.InnerText = comboBox1.Text.Trim();
UserList.AppendChild(pName);
list.Remove(comboBox1.Text.Trim());//刪除原來的
}
else
{
XmlElement pName = doc.CreateElement("UserName");
pName.InnerText = comboBox1.Text.Trim();
UserList.AppendChild(pName);
}
int userCnt = 0;
if (list.Count < 7)//設置保存用戶名的數量
{
userCnt = list.Count;
}
else
{
userCnt = list.Count - 1;
}
//將之前保存在XML中的用戶名再寫入XML文件
for (int i = 0; i < userCnt; i++)
{
XmlElement proName = doc.CreateElement("UserName");
proName.InnerText = list[i];
UserList.AppendChild(proName);
}
if (File.Exists(xmlPath))
{
File.SetAttributes(xmlPath, FileAttributes.Normal);
}
doc.Save(xmlPath);
File.SetAttributes(xmlPath, FileAttributes.Hidden);
}
private void Form1_Load(object sender, EventArgs e)
{
List<string> list = ReadXmlFile();/<string>
for (int i = 0; i < list.Count; i++)
{
comboBox1.Items.Add(list[i]);
}
if(comboBox1.Items.Count>0)
{
comboBox1.SelectedIndex = 0;
}
}
/// <summary>
/// 讀取xml文件
///
/// <returns>
private List<string> ReadXmlFile()/<string>
{
List<string> list = new List<string>();/<string>/<string>
if (File.Exists(xmlPath))
{
comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
XmlElement el = doc.DocumentElement;
XmlNodeList xnl = el.ChildNodes;
foreach (XmlNode item in xnl)
{
list.Add(item.InnerText);
}
}
return list;
}
閱讀更多 路馬編程 的文章