从XML文件填充文本框

时间:2016-03-04 12:12:01

标签: c# xml serialization save load

我将两个文本框保存为.XML文件。现在我想将它们加载到我的文本框中以便能够编辑它们。我也继承了Person类。有帮助吗?感谢

 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;
    }

修改

  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;
    }

我也创建了那个位..现在我需要的是从OpenBileDialog中打开一个文件,用BtnClick操作选择文件并加载文本框。感谢

1 个答案:

答案 0 :(得分:3)

加载Button_Click:

为您的按钮添加事件处理程序(此处我称之为button1):

button1.Click += button1_Click;

button1_Click你可以做到:

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);
        }
    }
}