C#: populate combobox with data (key:value) from an XML file.

I want to populate a combobox on a windows form with data from an XML file.

how to?
not much documentation, and I also searched past questions but no luck... all questions are in VB.net and/or more complex scenarios than what I need...

thanks!
zorba111Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

it_saigeDeveloperCommented:
Without seeing your dataset; something like this?

Form1.cs -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;

namespace EE_Q28708964
{
	public partial class Form1 : Form
	{
		readonly List<KeyValuePair<int, string>> pairs = new List<KeyValuePair<int, string>>();

		public Form1()
		{
			InitializeComponent();
		}

		private void OnLoad(object sender, EventArgs e)
		{
			XElement element = null;
			try
			{
				element = XElement.Load("DataFile.xml");
				pairs.AddRange((from elem in element.Descendants("pair") select new KeyValuePair<int, string>(elem.Attribute("key").GetAsInteger(), elem.Attribute("value").GetAsString())));
			}
			catch (Exception ex) 
			{ 
				Console.WriteLine(ex);
			}
			comboBox1.DataSource = pairs;
			comboBox1.ValueMember = "Key";
			comboBox1.DisplayMember = "Value";
		}
	}

	static class Extensions
	{
		public static int GetAsInteger(this XAttribute attribute)
		{
			int temp = -1;
			return (attribute != null && !int.TryParse(attribute.Value, out temp)) ? temp : -1;
		}

		public static string GetAsString(this XAttribute attribute)
		{
			return (attribute != null && !string.IsNullOrEmpty(attribute.Value)) ? attribute.Value : string.Empty;
		}
	}
}

Open in new window

Form1.Designer.cs -
namespace EE_Q28708964
{
	partial class Form1
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.comboBox1 = new System.Windows.Forms.ComboBox();
			this.SuspendLayout();
			// 
			// comboBox1
			// 
			this.comboBox1.FormattingEnabled = true;
			this.comboBox1.Location = new System.Drawing.Point(12, 12);
			this.comboBox1.Name = "comboBox1";
			this.comboBox1.Size = new System.Drawing.Size(260, 21);
			this.comboBox1.TabIndex = 0;
			// 
			// Form1
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(284, 261);
			this.Controls.Add(this.comboBox1);
			this.Name = "Form1";
			this.Text = "Form1";
			this.Load += new System.EventHandler(this.OnLoad);
			this.ResumeLayout(false);

		}

		#endregion

		private System.Windows.Forms.ComboBox comboBox1;
	}
}

Open in new window

DataFile.xml (with the 'Copy to Output Directory' property set to 'Copy Always')-
<?xml version="1.0" encoding="utf-8" ?>
<pairs>
	<pair key ="1" value="ONE" />
	<pair key ="2" value="TWO" />
	<pair key ="3" value="THREE" />
	<pair key ="4" value="FOUR" />
	<pair key ="5" value="FIVE" />
	<pair key ="6" value="SIX" />
	<pair key ="7" value="SEVEN" />
	<pair key ="8" value="EIGHT" />
	<pair key ="9" value="NINE" />
	<pair key ="10" value="TEN" />
</pairs>

Open in new window

Produces the following output -Capture.JPG-saige-
0
zorba111Author Commented:
Thanks saige....

Woah, some pretty complex stuff there for me!

my dataset:

<?xml version="1.0" encoding="Windows-1252"?><JobCategories><JobCategories><JobCatID>8</JobCatID><JobCategory>Accountancy &amp; Finance</JobCategory></JobCategories><JobCategories><JobCatID>20</JobCatID><JobCategory>Banking, Financial services &amp; Insurance</JobCategory></JobCategories><JobCategories><JobCatID>11</JobCatID><JobCategory>Beauty,Hair Care,Leisure &amp; Sport</JobCategory></JobCategories><JobCategories><JobCatID>9</JobCatID><JobCategory>Construction, Architecture &amp; Property</JobCategory></JobCategories><JobCategories><JobCatID>23</JobCatID><JobCategory>Customer Service, Call Centres &amp; Languages</JobCategory></JobCategories><JobCategories><JobCatID>13</JobCatID><JobCategory>Education, Childcare &amp; Training</JobCategory></JobCategories><JobCategories><JobCatID>6</JobCatID><JobCategory>Engineering &amp; Utilities</JobCategory></JobCategories><JobCategories><JobCatID>2</JobCatID><JobCategory>Environmental, Health &amp; Safety</JobCategory></JobCategories><JobCategories><JobCatID>27</JobCatID><JobCategory>General Management</JobCategory></JobCategories><JobCategories><JobCatID>1</JobCatID><JobCategory>Hotel &amp; Catering</JobCategory></JobCategories><JobCategories><JobCatID>16</JobCatID><JobCategory>HR &amp; Recruitment</JobCategory></JobCategories><JobCategories><JobCatID>3</JobCatID><JobCategory>IT</JobCategory></JobCategories><JobCategories><JobCatID>4</JobCatID><JobCategory>Legal</JobCategory></JobCategories><JobCategories><JobCatID>21</JobCatID><JobCategory>Marketing</JobCategory></JobCategories><JobCategories><JobCatID>17</JobCatID><JobCategory>Nursing, Healthcare &amp; Medical</JobCategory></JobCategories><JobCategories><JobCatID>7</JobCatID><JobCategory>Production, Manufacturing &amp; Materials</JobCategory></JobCategories><JobCategories><JobCatID>115</JobCatID><JobCategory>Public Sector</JobCategory></JobCategories><JobCategories><JobCatID>25</JobCatID><JobCategory>Publishing, Media &amp; Creative Arts</JobCategory></JobCategories><JobCategories><JobCatID>10</JobCatID><JobCategory>Retailing, Wholesaling &amp; Purchasing</JobCategory></JobCategories><JobCategories><JobCatID>24</JobCatID><JobCategory>Sales</JobCategory></JobCategories><JobCategories><JobCatID>26</JobCatID><JobCategory>Science, Pharmaceutical &amp; Food</JobCategory></JobCategories><JobCategories><JobCatID>114</JobCatID><JobCategory>Secretarial &amp; Admin</JobCategory></JobCategories><JobCategories><JobCatID>14</JobCatID><JobCategory>Security, Trades &amp; General Services</JobCategory></JobCategories><JobCategories><JobCatID>12</JobCatID><JobCategory>Social &amp; Not for Profit</JobCategory></JobCategories><JobCategories><JobCatID>5</JobCatID><JobCategory>Telecoms</JobCategory></JobCategories><JobCategories><JobCatID>19</JobCatID><JobCategory>Tourism, Travel &amp; Airlines</JobCategory></JobCategories><JobCategories><JobCatID>18</JobCatID><JobCategory>Transport, Warehousing &amp; Motor</JobCategory></JobCategories><JobCategories><JobCatID>28</JobCatID><JobCategory>Graduate</JobCategory></JobCategories><JobCategories><JobCatID>29</JobCatID><JobCategory>Executive</JobCategory></JobCategories><JobCategories><JobCatID>116</JobCatID><JobCategory>Motoring</JobCategory></JobCategories></JobCategories>

Open in new window


sorry about formatting...

code I tried so far:

            XmlDocument xmldocCategories = new XmlDocument();
            xmldocCategories.Load("JobCategories.xml");

            DataSet dsCategories = new DataSet();
            dsCategories.ReadXml("JobCategories.xml");

            //dsCategories.

            cboCategories.DataSource = dsCategories.Tables[0];
            //cboCategories.DataBind();

Open in new window


(this was in the form's "Load" event-handler)

and the output:

combo-box.jpg
0
it_saigeDeveloperCommented:
You were very close, the only thing you forgot was specifying your DisplayMember and ValueMember; e.g. -

Form1.cs -
using System;
using System.Data;
using System.Windows.Forms;

namespace EE_Q28708964
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			DataSet dsCategories = new DataSet();
			dsCategories.ReadXml("JobCategories.xml");
			cboCategories.DataSource = dsCategories.Tables[0];
			cboCategories.DisplayMember = "JobCategory";
			cboCategories.ValueMember = "JobCatID";
		}
	}
}

Open in new window

Form1.Designer.cs -
namespace EE_Q28708964
{
	partial class Form1
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.cboCategories = new System.Windows.Forms.ComboBox();
			this.SuspendLayout();
			// 
			// cboCategories
			// 
			this.cboCategories.FormattingEnabled = true;
			this.cboCategories.Location = new System.Drawing.Point(13, 13);
			this.cboCategories.Name = "cboCategories";
			this.cboCategories.Size = new System.Drawing.Size(259, 21);
			this.cboCategories.TabIndex = 0;
			// 
			// Form1
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(284, 261);
			this.Controls.Add(this.cboCategories);
			this.Name = "Form1";
			this.Text = "Form1";
			this.Load += new System.EventHandler(this.Form1_Load);
			this.ResumeLayout(false);

		}

		#endregion

		private System.Windows.Forms.ComboBox cboCategories;
	}
}

Open in new window

JobCategories.xml (with the 'Copy to Output Directory' property set to 'Copy Always') -
<?xml version="1.0" encoding="Windows-1252"?>
<JobCategories>
	<JobCategories>
		<JobCatID>8</JobCatID>
		<JobCategory>Accountancy &amp; Finance</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>20</JobCatID>
		<JobCategory>Banking, Financial services &amp; Insurance</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>11</JobCatID>
		<JobCategory>Beauty,Hair Care,Leisure &amp; Sport</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>9</JobCatID>
		<JobCategory>Construction, Architecture &amp; Property</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>23</JobCatID>
		<JobCategory>Customer Service, Call Centres &amp; Languages</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>13</JobCatID>
		<JobCategory>Education, Childcare &amp; Training</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>6</JobCatID>
		<JobCategory>Engineering &amp; Utilities</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>2</JobCatID>
		<JobCategory>Environmental, Health &amp; Safety</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>27</JobCatID>
		<JobCategory>General Management</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>1</JobCatID>
		<JobCategory>Hotel &amp; Catering</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>16</JobCatID>
		<JobCategory>HR &amp; Recruitment</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>3</JobCatID>
		<JobCategory>IT</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>4</JobCatID>
		<JobCategory>Legal</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>21</JobCatID>
		<JobCategory>Marketing</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>17</JobCatID>
		<JobCategory>Nursing, Healthcare &amp; Medical</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>7</JobCatID>
		<JobCategory>Production, Manufacturing &amp; Materials</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>115</JobCatID>
		<JobCategory>Public Sector</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>25</JobCatID>
		<JobCategory>Publishing, Media &amp; Creative Arts</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>10</JobCatID>
		<JobCategory>Retailing, Wholesaling &amp; Purchasing</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>24</JobCatID>
		<JobCategory>Sales</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>26</JobCatID>
		<JobCategory>Science, Pharmaceutical &amp; Food</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>114</JobCatID>
		<JobCategory>Secretarial &amp; Admin</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>14</JobCatID>
		<JobCategory>Security, Trades &amp; General Services</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>12</JobCatID>
		<JobCategory>Social &amp; Not for Profit</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>5</JobCatID>
		<JobCategory>Telecoms</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>19</JobCatID>
		<JobCategory>Tourism, Travel &amp; Airlines</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>18</JobCatID>
		<JobCategory>Transport, Warehousing &amp; Motor</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>28</JobCatID>
		<JobCategory>Graduate</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>29</JobCatID>
		<JobCategory>Executive</JobCategory>
	</JobCategories>
	<JobCategories>
		<JobCatID>116</JobCatID>
		<JobCategory>Motoring</JobCategory>
	</JobCategories>
</JobCategories>

Open in new window

Which produces the following output -Capture.JPG-saige-
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

it_saigeDeveloperCommented:
And if you want your categories ordered:
using System;
using System.Data;
using System.Windows.Forms;
using System.Linq;

namespace EE_Q28708964
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			DataSet dsCategories = new DataSet();
			dsCategories.ReadXml("JobCategories.xml");
			dsCategories.Tables[0].DefaultView.Sort = "JobCategory";
			cboCategories.DataSource = dsCategories.Tables[0];
			cboCategories.DisplayMember = "JobCategory";
			cboCategories.ValueMember = "JobCatID";
		}
	}
}

Open in new window

Which now produces the following output -Capture.JPG-saige-
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
zorba111Author Commented:
Hi Saige,

So I compared your Form1.Designer.cs with mine and came to the conclusion that there is nothing you added in here, its all generated code (correct?).

Next, I was concerned because my XML format was so different from yours. So I added these lines to check if my XML was being parsed into the DataSet correctly:

            String sColumnName = dsCategories.Tables[0].Columns[0].ColumnName;
            sColumnName = dsCategories.Tables[0].Columns[1].ColumnName;

Open in new window


So those diagnostic lines showed me the XML was being parsed okay. So it was probably about display in the Combo Box. So I looked into those 2x combo box properties you were setting....

I added these two lines, for key and value, *after* assigning the DataSource:

            cboCategories.DataSource = dsCategories.Tables[0];
            cboCategories.ValueMember = dsCategories.Tables[0].Columns[0].ToString();
            cboCategories.DisplayMember = dsCategories.Tables[0].Columns[1].ToString();

Open in new window


This did the trick, it was more to do with setting the ComboBox than correcting anything to do with XML parsing (as I first thought)...

thanks!
0
zorba111Author Commented:
Sorry, I didn't see your updated answer till now! (not the first time had problems with EE page updates...)

Ok, thanks, and the sort bit is useful too.
many thanks!!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.