1

i am new to ASP.NET,

i am making Country, state dropdownlist.

for eg: For particular country, i will read states of that country from XML file.

i am unable to fetch states of required country in my Dropdownlist...

here is my code snippet in XMLFile.xml

 <?xml version="1.0" encoding="utf-8" ?>
<countrys>

  <country name="India">
    <state value1="Maharashtra"></state>
    <state value2="Kashmir"></state>
    <state value3="Goa"></state>
  </country>

  <country name="Sri Lanka">
    <state value1="Kanady"></state>
    <state value2="Colombo"></state>
    <state value3="Galle"></state>
  </country>

  <country name="Australia">
    <state valu1e="Sydney"></state>
    <state value2="Perth"></state>
    <state value3="Melbourne"></state>
  </country>

  <country name="South Africa">
    <state value1="Capetown"></state>
    <state value2="Johanusburg"></state>
      <state value3="Durban"></state>
  </country>

</countrys>

and code in Country.aspx.cs

 public partial class Country : System.Web.UI.Page
   {
       protected void Page_Load(object sender, EventArgs e)
       {

            if (!IsPostBack)
            {
                LoadDropdown();
            }
     }

    protected void LoadDropdown()
    {
            DataSet ds = new DataSet();
            ds.ReadXml (Server.MapPath("XMLFile.xml"));

            DropDownListCountry.DataTextField = "country_text";

            DropDownListCountry.DataSource = ds;
            DropDownListCountry.DataBind();
            DropDownListCountry.Items.Insert(0,new ListItem(" Select ","0"));
        }
     }

    protected void DropDownListCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
            string  st = (DropDownListCountry.SelectedIndex).ToString();

             XDocument main = XDocument.Load(@"XMLFile.xml");

        var query = from state in doc.Descendants("countrys").Elements("country")
                    where st == state.Value
                    select state.NextNode;

        DropDownListState.DataSource = query;
        DropDownListState.DataBind();     
    }
}

ERROR : Object reference not set to an instance of an object.

Thanks In Advance !!

5
  • which line do you get the error Commented Apr 19, 2012 at 9:36
  • my linq query gives me null value.. can you plz check that... Commented Apr 19, 2012 at 9:38
  • a) There is no element in your xml with name "country_text" b) Your states are not within the country element.. c) "state" has no value but "text" inside state has value..Please modify your xml properly before working with it Commented Apr 19, 2012 at 9:39
  • 1
    your xml document doesn't imply a relationship between a country and the states that are under it. perhaps a structure like <country name="country1"><state name="state1"/><state name="state2"/></country> suits better Commented Apr 19, 2012 at 9:40
  • i wrote my xnl file as you suggested, and tried this query, but still i not getting o/p: var query = from user in doc.Descendants("state") where st == user.Element("state").Value select user.NextNode; Commented Apr 19, 2012 at 10:42

3 Answers 3

2

OK here is the solution: First few changes in the xml, the attribute 'value1' in the state element should be value for all. So the new XML is:

<?xml version="1.0" encoding="utf-8" ?>
<countrys>

  <country name="India">
    <state value="Maharashtra"></state>
    <state value="Kashmir"></state>
    <state value="Goa"></state>
  </country>

  <country name="Sri Lanka">
    <state value="Kanady"></state>
    <state value="Colombo"></state>
    <state value="Galle"></state>
  </country>

  <country name="Australia">
    <state value="Sydney"></state>
    <state value="Perth"></state>
    <state value="Melbourne"></state>
  </country>

  <country name="South Africa">
    <state value="Capetown"></state>
    <state value="Johanusburg"></state>
    <state value="Durban"></state>
  </country>

</countrys>

Now come to ASPX page: You should have two drop down lists with AutoPostBack set to true

<asp:DropDownList ID="DropDownListCountry" runat="server" AutoPostBack="true"
    onselectedindexchanged="DropDownListCountry_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="DropDownListState" runat="server" AutoPostBack="true"
    onselectedindexchanged="DropDownListState_SelectedIndexChanged">
</asp:DropDownList>

Now in the Code behind:
Call LoadCountryDropDown to populate Country - I am using LINQ to XML here as well instead of data set

protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                LoadCountryDropDown();
            }

        }
        void LoadCountryDropDown()
        {
            XDocument doc = XDocument.Load(Server.MapPath("test.xml"));

            DropDownListCountry.DataSource = from t in doc.Descendants("countrys").Elements("country")
                                             select new
                                             {
                                                 Name = t.Attribute("name").Value
                                             };

            DropDownListCountry.DataTextField = "Name";
            DropDownListCountry.DataValueField = "Name";
            DropDownListCountry.DataBind();
            DropDownListCountry.Items.Insert(0, new ListItem(" Select ", "0"));
        }

LoadStateDropDown() method to populate State drop down on Selected index changed event of country drop down

private void LoadStateDropDown(string p)
    {
        XDocument doc = XDocument.Load(Server.MapPath("test.xml"));

        var statequery = from t in doc.Descendants("countrys").Elements("country")
                                         where t.Attribute("name").Value.Equals(p)
                                         select new
                                         {
                                             State = t.Elements("state").Attributes("value").ToList()
                                         };

        DropDownListState.DataSource = statequery.First().State;
        DropDownListState.DataTextField = "value";
        DropDownListState.DataValueField = "value";
        DropDownListState.DataBind();
        DropDownListState.Items.Insert(0, new ListItem(" Select ", "0"));
    }

In the end you have event handler for drop down list

 protected void DropDownListCountry_SelectedIndexChanged(object sender, EventArgs e)
        {

            LoadStateDropDown(DropDownListCountry.SelectedValue);
        }
  protected void DropDownListState_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


(Please rename countrys to countries in xml)

Sign up to request clarification or add additional context in comments.

Comments

0
  XDocument main = XDocument.Load(@"data.xml"); 
        var query = from state in main.Descendants("countrys").Elements("country")
                    where st == state.Value
                    select state.NextNode; 

Comments

0

Just have one method to fill the dropdown. The code will be easier to understand and maintain. Pass null as parameter if there is no selected country (at first page load). According to the xml file above you seem to have written the wrong strings to select the states. There was an error with selectedindex. Use selected value. Hope this helps:

     protected void Page_Load(object sender, EventArgs e)
       {

            if (!IsPostBack)
            {
                LoadDropdown(null);
            }
     }
     protected void LoadDropdown(string selectedCountry)
        {
                XDocument main = XDocument.Load(@"XMLFile.xml");
                if(selectedCountry != null)
                {
                        DropDownListCountry.DataSource = from state in main.Element("countries").Element(selectedConty).Elements("state")
                        where state.Value = selectedCountry
select state.Value;
                }
                else
                {
                        DropDownListCountry.DataSource = null;
                }
                DropDownListCountry.DataBind();
                DropDownListCountry.Items.Insert(0,new ListItem(" Select ","0"));
            }
         }

        protected void DropDownListCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
                string  st = DropDownListCountry.SelectedValue;

                 LoadDropdown(st);
        }

2 Comments

.Element(selectedConty).Element("state") this will return null , there is no element with name state for a country element
selectedCountry is a parameter that I have introduced to the method. (read the code) @Flowerking: thanks I have corrected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.