从xml文件写入和读取数据
本文关键字:读取 数据 xml 文件 | 更新日期: 2023-09-27 18:10:36
public partial class Form2 : Form
{
DataTable dt = new DataTable();
DataRow dr;
public Form2()
{
InitializeComponent();
dt.Columns.Add("ServerName");
dt.Columns.Add("UserId");
dt.Columns.Add("Password");
dt.Columns.Add("DatabaseName");
}
private void btn_save_Click(object sender, EventArgs e)
{
dt.TableName = "DER";
dr = dt.NewRow();
dr["ServerName"] = tb_serverName.Text.Trim();
dr["UserId"] = tb_userId.Text.Trim();
dr["Password"] = tb_pwd.Text.Trim();
dr["DatabaseName"] = tb_dbName.Text.Trim();
dt.Rows.Add(dr);
dt.WriteXml("D:''DatabaseInfo.xml");
dt.Clear();
}
private void btn_back_Click(object sender, EventArgs e)
{
dt.ReadXml("D:''DatabaseInfo.xml");
foreach (DataRow dr in dt.Rows)
{
tb_serverName.Text = dr["ServerName"].ToString();
tb_userId.Text = dr["UserId"].ToString();
tb_pwd.Text = dr["Password"].ToString();
tb_dbName.Text = dr["DatabaseName"].ToString();
}
}
}
单击btn_save
数据保存在XML文件中,但是当我单击btn_back
时,在表单字段中看不到数据。我必须在btn_back_click
中正确做什么?
使用这样的DataSet
可以解决您的问题:
private void btn_back_Click(object sender, EventArgs e)
{
string path = "D:''DatabaseInfo.xml";
var xmlFile = XmlReader.Create(path);
DataSet ds = new DataSet();
ds.ReadXml(xmlFile);
foreach (DataRow dr in ds.Tables[0].Rows)
{
tb_serverName.Text = dr["ServerName"].ToString();
tb_userId.Text = dr["UserId"].ToString();
tb_pwd.Text = dr["Password"].ToString();
tb_dbName.Text = dr["DatabaseName"].ToString();
}
}