How to bind an XmlDocument to a DropDownList?

B

Bob

Is there a way to bind an XmlDocument object (or XmlNodeList) directly to a
DropDownList in the code behind? I know it can probably be done using
DataBinder to specify the items in the aspx but I need to do this in code
behind C# code. I'm looking for a way to bind it without having to convert
the Xml into DataTable or ArrayList etc first.

Bob
 
C

Craig Deelsnyder

Is there a way to bind an XmlDocument object (or XmlNodeList) directly
to a
DropDownList in the code behind? I know it can probably be done using
DataBinder to specify the items in the aspx but I need to do this in code
behind C# code. I'm looking for a way to bind it without having to
convert
the Xml into DataTable or ArrayList etc first.

Bob

Sure, you can do the following:

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if (!IsPostBack)
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.InnerXml =
"<root><item>1</item><item>2</item><item>3</item></root>";
DropDownList1.DataSource = doc.ChildNodes[0].ChildNodes;
DropDownList1.DataTextField = "InnerText";
DropDownList1.DataValueField = "InnerText";
DropDownList1.DataBind();

}
}

the problem comes in depending on where you want your text/value to come
from. If you have an attribute on these nodes whose value you wanted to
use instead of InnerText, you can't with the code I gave, as DataTextField
and DataValueField must contain the name of a property of the current item
in the bound collection. You can't say Attributes["key"] for example,
only Attributes (which doesn't do much for you).

In that case, you'd have to tie into the DataBinding event of the dropdown
and set the text/value manually there.

Otherwise, revert to using the codefront:

http://weblogs.asp.net/kaevans/archive/2003/07/04/9713.aspx
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top