这是我的XML文件,我想在文本框中输入ID并将其他数据输入其他文本框。
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Users>
<User Name="aa" Occupation="dd" Date_Of_Birth="123456" NIC="123123"
ID="79461" />
<User Name="Ali Rasheed" Occupation="Student" Date_Of_Birth="111694" NIC="4550246607037" ID="12661" />
<User Name="Asif Rasheed" Occupation="Civil Engineer" Date_Of_Birth="241190" NIC="4550346603073" ID="90939" />
<User Name="Sadaf Sohail" Occupation="Teacher" Date_Of_Birth="112233" NIC="445566677999" ID="72508" />
<User Name="Shahnaz Bano" Occupation="Retired Principle" Date_Of_Birth="223311" NIC="454564974149" ID="65199" />
<User Name="Alex" Occupation="Programmer" Date_Of_Birth="111694" NIC="45522002211447" ID="44534" />
</Users>
这是我的代码
var data = XElement.Load(@"C:\GenesisSolutionsCRMSBuild12101\XMLDatabase.xml").Descendants("User");
foreach (var textbox in Controls.OfType<TextBox>())
{
var value = data.FirstOrDefault(v => v.Attribute("ID").Value == textbox.Name.Replace("txt", "").ToLower());
if (value != null)
{
textBox1.Text = value.Attribute("Name").Value;
textBox2.Text = value.Attribute("Occupation").Value;
textBox3.Text = value.Attribute("Date_Of_Birth").Value;
textBox4.Text = value.Attribute("NIC").Value;
}
}
答案 0 :(得分:0)
无需遍历所有控件。它就像从ID文本框中读取Text
属性一样简单:
var data = XElement.Load(@"C:\GenesisSolutionsCRMSBuild12101\XMLDatabase.xml")
.Descendants("User");
// Get the ID the user entered
string id = idTextBox.Text;
var user = data.FirstOrDefault(v => v.Attribute("ID").Value == id);
if (user != null)
{
textBox1.Text = user.Attribute("Name").Value;
textBox2.Text = user.Attribute("Occupation").Value;
textBox3.Text = user.Attribute("Date_Of_Birth").Value;
textBox4.Text = user.Attribute("NIC").Value;
}
您可能需要考虑将textBoxN
重命名为更有用的内容,例如nameTextBox
。