I want the value of a specific attribute (e.g. title_1 in my html example) which I select with a combobox in visual studio. I have a problem with my looping through the attributes. It works only with title_1 and stops after the title_1.
Following my html-file
<div id="main">
<div id="title_1">
<p>product name</p>
</div>
<div id="title_2">
<p>product highlights</p>
</div>
<div id="content">
<p>product price - product size - product date</p>
</div>
</div id="main">
As a result, if I selcet title_2 in the ComboBox1 I want product highlights in my TextBox1. If I select content in the ComboBox1 I want product price - product size - product date in my TextBox1. Until now it works only with title_1, here I got product name in my TextBox1
Here my code
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim xelement As XElement = XElement.Load("myPATH\file.html")
Dim attributes As IEnumerable(Of XElement) = xelement.Descendants("div")
For Each item As XElement In attributes
If attributes.@id = ComboBox1.Text Then
TextBox1.Text = attributes.Value
End If
Next
End Sub
End Class
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub
It's probably just a typo. You iterate each item
in attributes
, but then you don't access item
, rather attributes
.
For Each item As XElement In attributes
If attributes.@id = ComboBox1.Text Then
TextBox1.Text = attributes.Value
End If
Next
Change it to this
For Each item As XElement In attributes
If item.@id = ComboBox1.Text Then
TextBox1.Text = item.Value
End If
Next
Fixed.
Also, your html included an attribute in the closing tag. Is that valid? I had to remove it to make the code work.
</div id="main">
I would add this line to clear TextBox1 prior to matching the value, in case there is no match
TextBox1.Clear()
You probably load the attributes into the ComboBox. But if you don't, use this. It would make the question more complete if you included it
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim xelement As XElement = XElement.Load("myPATH\file.html")
Dim attributes As IEnumerable(Of XElement) = xelement.Descendants("div")
ComboBox1.DataSource = attributes.Select(Function(a) a.@id).ToList()
End Sub