Binding DataSource DropDownList with XPathSelect
Hello!
I have XML like this:
<Root>
<MainSection>
<SomeNode>Some Node Value</SomeNode>
<SomeOtherNode>Some Other Node Value</SomeOtherNode>
<Areas>
<Area someattribute="aaa" name="Alpha" value="0" />
<Area someattribute="bbb" name="Beta" value="1" />
<Area someattribute="ddd" name="Delta" value="2" />
</Areas>
</MainSection>
</Root>
I have a FormView in my web form that has many values ββbound. I would like to bind the child nodes of Areas to the DropDownList like this:
<asp:FormView ID="MyFormView" runat="server" DataSourceID="MyXmlDataSource">
<ItemTemplate>
<h1><%# XPath("SomeNode")%></h1>
<asp:Label ID="MyLabel" runat="server" AssociatedControlID="MyDdl" Text='<%# XPath("SomeOtherNode")%>' />
<asp:DropDownList ID="MyDdl" runat="server" DataSource='<%# XPathSelect("Areas/*") %>' DataTextField="name" DataValueField="value"></asp:DropDownList>
</ItemTemplate>
</asp:FormView>
<asp:XmlDataSource ID="MyXmlDataSource" runat="server" XPath="Root/MainSection" />
Unfortunately, instead of seeing the data that I expect in the dropdown, I see 3 entries with "Area" as text and no values.
I know my XML is fine because for testing purposes I tried to expose the Repeater element on the page like this:
<asp:Repeater ID="MyRepeater" runat="server" DataSource='<%# XPathSelect("Areas/*") %>'>
<ItemTemplate>
<%# XPath("@name") %> - <%# XPath("@value") %><br />
</ItemTemplate>
</asp:Repeater>
And it worked fine.
Is there something I am doing wrong when binding to a dropdown, possibly with the DataTextField and DataValueField properties?
source to share
XPathSelect does not return a DataSource that can be directly linked. Just like you had a FormView binding and your bindings were using XPath ("...") rather than Bind ("..."), you have the same problem with DropDownList. Either create a standard DataSource with your attributes and bind the DDL to that, or roll your own HTML with a ListView that generates select option tags or something.
source to share