binding combo box to xml file

acorn

Active member
Joined
Mar 8, 2008
Messages
32
Programming Experience
5-10
Hi there. i have an xml file that looks like:
VB.NET:
<?xml version="1.0"?>
<ROWSET>
 <ROW>
  <RESPONSE>No</RESPONSE>
  <VALUE>0</VALUE>
 </ROW>
 <ROW>
  <RESPONSE>Yes</RESPONSE>
  <VALUE>1</VALUE>
 </ROW>
 <ROW>
  <RESPONSE>Do Not Know</RESPONSE>
  <VALUE>777</VALUE>
 </ROW>
</ROWSET>
I'd like to have the response text show up as the display member property and the value to be the data that's actually saved in the back end.
I have some code to read the xml file ... but i'm not sure if this is the best way to do it. I'm also not sure how to load / save the associated values when an item is actually selected.

My code looks like:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim xmlFile As String = "reference tables\yndnk.xml"
Dim xmlDoc As XmlDocument

Dim xmlTr As New XmlTextReader(xmlFile)

While xmlTr.Read
XmlNodeType.Element Then
If xmlTr.Name = "RESPONSE" AndAlso xmlTr.NodeType = XmlNodeType.Element Then
ComboBox1.Items.Add(xmlTr.ReadString)
End If
End While
xmlTr.Close()
End Sub
 
I would suggest using a DataSet's ReadXml and binding the ComboBox to it.

VB.NET:
	Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
	Handles MyBase.Load

		Dim ds As New DataSet
		ds.ReadXml("C:\Temp\Test.xml")

		With Me.ComboBox1
			.DataSource = ds.Tables("ROW")
			.DisplayMember = "RESPONSE"
			.ValueMember = "VALUE"
		End With

	End Sub

Displaying the ValueMember.

VB.NET:
	Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
	Handles ComboBox1.SelectedIndexChanged

		MessageBox.Show(CType(sender, ComboBox).SelectedValue.ToString())

	End Sub
 
Back
Top