简体   繁体   English

C#:通过DataSet将XML绑定到ComboBox

[英]C#: Bind XML to ComboBox via DataSet

I am trying to get this code work for about 2 hours =( I am new to C# and don't know all the .NET library classes. 我试图使这段代码工作大约2个小时=(我是C#的新手,并且不了解所有.NET库类。

The target is to populate XML data to comboBox 目标是将XML数据填充到comboBox

DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable("table1");
dataTable.Columns.Add("col1", typeof(string));
dataSet.Tables.Add(dataTable);

StringReader strR = new StringReader("<root><parm1>val1</parm1><parm2>val2</parm2></root>");

dataSet.ReadXml(strR);

comboBox1.DataSource = dataSet.Tables[0];
comboBox1.DisplayMember = "col1";
comboBox1.ValueMember = "col1";

Well, it doesn't work as expected. 好吧,它没有按预期工作。 The ComboBox should show val1 val2 ComboBox应该显示val1 val2

I don't really understand how column names of DataTable in a DataSet are related to XML-Tags... Maybe that's the point? 我不太了解DataSet中DataTable的列名如何与XML-Tags相关联……也许这就是重点吗?

Thank You in advance! 先感谢您!

The following should work: 以下应该工作:

DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable("table1");
dataTable.Columns.Add("col1", typeof(string));
dataSet.Tables.Add(dataTable);

StringReader strR = new StringReader("<root><table1><col1>val1</col1></table1><table1><col1>val2</col1></table1></root>");

dataSet.ReadXml(strR);

comboBox1.DataSource = dataSet.Tables[0];
comboBox1.DisplayMember = "col1";
comboBox1.ValueMember = "col1";

The names of the tables and the columns need to be consistent between your C# objects and XML data. 表和列的名称在C#对象和XML数据之间必须保持一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM