如何在列表框中显示XML并将其传递给C#中的文本框?
我正在努力制作一个基本的C#应用程序,它从XML文件中获取大量项目,在列表框中显示“title”节点,并且在选择某个标题时,在文本框中显示该项目的其他节点。文本框用于允许用户编辑XML内容并保存更改 我认为我的问题很基本:列表框工作正常,但是当在列表框中选择新标题时,文本框不会更新。我想它不应该太复杂,但对我来说,它是-我真的被困在这里 我知道像这样的问题经常会出现,但在我看来,大多数问题都不精确或过于复杂:我(显然)是C#新手,并且非常喜欢让代码尽可能简单和透明 我的XML示例:如何在列表框中显示XML并将其传递给C#中的文本框?,c#,xml,listbox,C#,Xml,Listbox,我正在努力制作一个基本的C#应用程序,它从XML文件中获取大量项目,在列表框中显示“title”节点,并且在选择某个标题时,在文本框中显示该项目的其他节点。文本框用于允许用户编辑XML内容并保存更改 我认为我的问题很基本:列表框工作正常,但是当在列表框中选择新标题时,文本框不会更新。我想它不应该太复杂,但对我来说,它是-我真的被困在这里 我知道像这样的问题经常会出现,但在我看来,大多数问题都不精确或过于复杂:我(显然)是C#新手,并且非常喜欢让代码尽可能简单和透明 我的XML示例: <?x
<?xml version='1.0'?>
<book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Franklin</last-name>
</author>
<price>8.99</price>
</book>
<book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
</book>
<book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
<title>The Gorgias</title>
<author>
<name>Plato</name>
</author>
<price>9.99</price>
</book>
</bookstore>
在这里,在文本框部分,我尝试了几乎所有的方法
WFA文件包含一个加载XML文件的按钮、一个列表框和一个文本框(也许每个XML节点都有一个文本框更好)加载XML时,将书籍放入列表中 建议使用linq2xml(
XElement
),因为它比传统的XmlDocument
更方便
private void ButtonLoad_Click(object sender, EventArgs e)
{
var xml = XElement.Load("books.xml");
bookList = xml.Elements("book").ToList();
foreach (var book in bookList)
{
string title = book.Element("title").Value;
listBox.Items.Add(title);
}
}
其中,List bookList
是一个表单字段
在事件处理程序中,按索引从列表中检索书籍
private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
var book = bookList[listBox.SelectedIndex];
textBox.Text =
"Genre: " + book.Attribute("genre").Value + Environment.NewLine +
"Price: " + book.Element("price").Value;
// Put other values to textbox (set Multiline = true)
}
当然,您可以使用多个文本框(或标签)
等等。非常感谢。这正是我所希望的:简短而清晰——这真是一个很大的帮助。
private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
var book = bookList[listBox.SelectedIndex];
textBox.Text =
"Genre: " + book.Attribute("genre").Value + Environment.NewLine +
"Price: " + book.Element("price").Value;
// Put other values to textbox (set Multiline = true)
}
textBoxGenre.Text = "Genre: " + book.Attribute("genre").Value;
textBoxPrice.Text = "Price: " + book.Element("price").Value;