-
Filling a combobox
Hello. I am trying to fill a combobox with data from an xml file. I have it setup on form load to call a loadXMLdata function. In the loadXMLdata function it reads the xml file. I would like to know how I would return each of the elements to populate the combobox. I have mostly done php work and in php i could do an array like this: array[book] = "VB.Net Programming". Is there a way to do something like this with an array such as xmlData("Server 1") = "255.255.255.255"
HTML Code:
<config>
<connection>
<servers>
<server label="Server 1" data="255.255.255.255" />
<server label="Server 2" data="255.255.255.255" />
<server label="Server 3" data="255.255.255.255" />
<server label="Server 4" data="255.255.255.255" />
<server label="Server 5" data="255.255.255.255" />
<server label="Server 6" data="255.255.255.255" />
</servers>
</connection>
</config>
Code:
'Login Form
Imports LoginTo.Functions
Public Class frmLogin
Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Load servers from xml file
'Maybe loop thru array and add items to comboBox
'cmbxServer.Items.Add(loadServers("C:\servers.xml"))
End Sub
End Class
Code:
'LoginTo.Functions
Imports System.IO
Imports System.Xml
Class Functions
Shared Function loadServers(ByVal serversXML As String) As Array
Try
Dim Doc As New FileStream(serversXML, FileMode.Open, FileAccess.Read)
Dim xmlDoc As XmlReader = XmlReader.Create(Doc)
Dim xmlData() As String
Dim counter As Integer
While xmlDoc.Read()
If xmlDoc.IsStartElement Then
If xmlDoc.IsEmptyElement Then
'Populate the combobox perhaps by returning xmlData array
'xmlData(counter)
End If
End If
End While
'Return xmlData array somehow
Return Nothing
Catch ex As Exception
MessageBox.Show("Error reading server file", ErrorToString, MessageBoxButtons.OK)
End Try
End Function
End Class
I know there are some things missing in my code like setting the counter integer. If you know an easier/faster/more efficient way of doing what I'm trying to do feel free to give advice. Thanks
PS I am new to vb.net programming and am learning as I go.
-
Re: Filling a combobox
You actually don't need to do all that code just to read an XML file in VB. VB has xml literals and has awesome support for XML unlike any other language I have used.
Here is an example assuming that your xml file is called data.xml and is in the same directory as the exe.
Code:
'LOAD XML DOCUMENT
Dim myDocument As XDocument = XDocument.Load(Application.StartupPath & "\data.xml")
'LOOP EACH <SERVER> NODE FOUND UNDER THE <SERVERS> NODE
'AND ADD THE LABEL AND DATA ATTRIBUTE TO THE LISTBOX
For Each ServerNode As XElement In myDocument.Root...<servers>.Nodes
ListBox1.Items.Add(ServerNode.Attribute("label").Value & " - " & ServerNode.Attribute("data").Value)
Next