简体   繁体   中英

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.

The target is to populate XML data to 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

I don't really understand how column names of DataTable in a DataSet are related to XML-Tags... Maybe that's the point?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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