写作&从xml文件中读取数据

时间:2015-08-31 13:21:21

标签: c# windows forms

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中做些什么?

1 个答案:

答案 0 :(得分:1)

使用这样的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();
   }
}