Populate City DropDown using XML and Filter on select index changed


.aspx page:

                <asp:DropDownList ID="ddlCity" runat="server" AutoPostBack="True"
        onselectedindexchanged="ddlCity_SelectedIndexChanged"></asp:DropDownList>

<asp:Literal ID="ltAddress" runat="server"></asp:Literal>
<asp:Literal ID="ltCity" runat="server"></asp:Literal>


protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDropDown();
        }
    }


protected void BindDropDown()
    {
        XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("myCityDetails.xml"));
        DataSet ds = new DataSet();
        ds.ReadXml(xmlreader);
        xmlreader.Close();
        if (ds.Tables.Count != 0)
        {
            ddlCity.DataSource = ds;
            ddlCity.DataTextField = "name";
            ddlCity.DataValueField = "id";
            ddlCity.DataBind();
        }
    }


//On Select Index Chanage of City, w.r.t we are going to populate Address, City
    protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
    {
        XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("myCityDetails.xml"));
        DataSet ds = new DataSet();
        ds.ReadXml(xmlreader);

        //Getting the dataset into DataView for filter purpose..
        DataView dv = ds.Tables[0].DefaultView;
        //passing the City Id
        dv.RowFilter = "id=" + ddlCity.SelectedValue;

        xmlreader.Close();
        if (dv != null)
        {
           
            foreach (DataRowView drv in dv)
            {
                ltAddress.Text = drv.Row["address"].ToString();
                ltCity.Text = drv.Row["name"].ToString();
            }
        }
    }

Xml file (myCityDetails.xml)
xml version="1.0" encoding="utf-8" ?>
<cities>
  <city>
    <name>Mumbai</name>
    <address>GateWay of India</address>
    <id>1</id>
  </city>
  <city>
    <name>Delhi</name>
    <address>Pragati Maidan</address>
    <id>2</id>
  </city>
  <city>
    <name>Banglore</name>
    <address>Cross Park</address>
    <id>3</id>
  </city>
  <city>
    <name>Chennai</name>
    <address>Tirupati Complex</address>
    <id>4</id>
  </city>
</cities>

Comments