Luke_i
Luke_i

Reputation: 163

Populate Text boxes from XML File

I am saving two text boxes as an .XML file. Now I want to Load them into my text boxes to be able to edit them. I am also inheriting fron a Person class. Any help? Thanks

 public partial class TeacherForm : Form
{
    public TeacherForm()
    {
        InitializeComponent();
    }

    private void tSavebtn_Click(object sender, EventArgs e)

    {
        try
        {
            Teacher teacher = new Teacher();
            teacher.Name1 = tNametxtBox.Text;
            teacher.ID1 = tIDtxtBox.Text;
            TeacherXML.Save(teacher);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

 public class TeacherXML
{
    private const string DataRepositoryFolder = "data\\Teachers\\";
    private const string FileExtension = ".xml";

    public static bool Save(Teacher teacher)
    {
        XmlSerializer xs = new XmlSerializer(typeof(Teacher));

        string targetPath = GetRepositoryFilePath(teacher.ID1);

        using (StreamWriter sw = new StreamWriter(targetPath, false, Encoding.UTF8))
        {
            xs.Serialize(sw, teacher);
        }
        return true;
    }

EDIT:


  public static Teacher Load(string ID)
    {
        string targetPath = GetRepositoryFilePath(ID);

        if (File.Exists(targetPath))
        {
            XmlSerializer xs = new XmlSerializer(typeof(Teacher));
            using (StreamReader sr = new StreamReader(targetPath))
            {
                return xs.Deserialize(sr) as Teacher;
            }
        }

        return null;
    }

I also created that bit.. all I need now is to Open a File from example the OpenFileDialog with a BtnClick action choose the file and load the text Boxes. Thanks

Upvotes: 2

Views: 410

Answers (1)

NoName
NoName

Reputation: 8025

To load on Button_Click:

Add event handler to your button (here I call it button1):

button1.Click += button1_Click;

In your button1_Click you can do:

private void button1_Click_1(object sender, EventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Filter = "XML Files|*.xml";
    if(ofd.ShowDialog()== System.Windows.Forms.DialogResult.OK)
    {
        try
        {
            XmlSerializer xs = new XmlSerializer(typeof(Teacher));
            using (FileStream sr = new FileStream(ofd.FileName, FileMode.Open))
            {
                var teacher = xs.Deserialize(sr) as Teacher;

                tNametxtBox.Text = teacher.Name1;
                tIDtxtBox.Text = teacher.ID1;
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

Upvotes: 3

Related Questions