Wednesday, 11 January 2012

How to bind a drop down list with an xml with the items of the dropdown list being sorted?

Lets assume we have an XML file which looks like this
<Sates>
<State>
<ID>1</ID>
<Name>Orissa</Name>
  </State>

<State>
<ID>2</ID>
<Name>Karnataka</Name>
</State>

<State>
<ID>3</ID>
<Name>Kolkata</Name>
</State>

<State>
<ID>4</ID>
<Name>A.P.</Name>
</State>

<State>
<ID>5</ID>
<Name>Bihar</Name>
</State>
</Sates>

To bind this xml with a dropdown list(say "ddlXML") we have to bind this xml with a dataset.
DataSet dsXML = new DataSet();

dsXML.ReadXML(Server.MapPath("~/XMLFiles/State.xml"))(the xml file State.xml is present inside XMLFiles folder inside project directory)

Create a DataView to out of this DataSet that will provide the sorting option and than bind this DataView with the dropdown

DataView dvXML = dsXML.Tables[0].DefaultView();
dvXML.Sort = "Name";

Now bind this DataView with the dropdown list
ddlXML.DataSource = dvXML;

ddlXML.DataBind();

DataView can be accessed through a DefaultView property on DataTable. DataView class allows us to sort and filter data but not store it.We can also use the DataView class to sort filtered inputted data to the database.

Happy Coding :)

No comments:

Post a Comment