使用C#将在不同控件中输入的值动态添加到xml中

时间:2018-09-24 11:03:17

标签: c# xml

我正在尝试将控件中的值插入xml,但是记录正在被上一个覆盖,该记录只有一个条目保留在xml文件中。请给我解决方案,我的代码如下:

namespace StudentApplicationForm
{

 public class information

 {

private String txtbox1;

 private String txtbox2;

 private String txtbox3;

 public String StudentName

 {

  get { return txtbox1; }

 set{  txtbox1 = value; }
}

        public String StudentId
        {
            get { return txtbox2; }
            set{ txtbox2 = value; }
        }
     public String StudentBranch
        {
            get { return txtbox3; }
            set { txtbox3 = value; }
        }


    }

}//getter and setter methods



and the file actual insert logic is written is:


 public void ok_Click(object sender, EventArgs e)
        {
            try

            {

    information info = new information();

    List<information> i1 = new List<information>();

      XmlSerializer serial = new XmlSerializer(typeof(List<information>));

                info.StudentName = textBox1.Text;//id of control

                info.StudentId = textBox2.Text;

             if (radioButton1.Checked)

                 {
                    info.StudentBranch = radioButton1.Text;
                 }

               if (radioButton2.Checked)

                  {

                   info.StudentBranch = radioButton2.Text;
              }
                  if (radioButton3.Checked)
         {
             info.StudentBranch = radioButton3.Text;
          }

        i1.Add(info);

 using (FileStream fs = newFileStream(Environment.CurrentDirectory + "\\mynew.xml", FileMode.Create, FileAccess.Write))

         {
                   serial.Serialize(fs, i1);
                    MessageBox.Show("Created");
      }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

1 个答案:

答案 0 :(得分:1)

您尝试过这样吗

 i1.Add(new information{ StudentName = info.StudentName, StudentId = info.StudentId,  StudentBranch = info.StudentBranch});