从 XML 文件填充文本框
Posted
技术标签:
【中文标题】从 XML 文件填充文本框【英文标题】:Populate Text boxes from XML File 【发布时间】:2016-03-04 12:12:01 【问题描述】:我将两个文本框保存为 .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;
我也创建了那个位.. 我现在需要的是从示例 OpenFileDialog 中打开一个文件,使用 BtnClick 操作选择文件并加载文本框。谢谢
【问题讨论】:
【参考方案1】:在 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);
【讨论】:
我需要 btnClick 操作上的 OpenFileDialog...这不在 btnClick 操作中...我想 XD 谢谢以上是关于从 XML 文件填充文本框的主要内容,如果未能解决你的问题,请参考以下文章