Reputation: 117
I am populating one DDL with another if we select country name in the DDL corresponding state must appear in another DDL below is my code
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string st = (DropDownList1.SelectedIndex).ToString();
XDocument main = XDocument.Load((Server.MapPath(@"XMLFile1.xml")));
var query = from user in main.Descendants("country")
where st == user.Element("state").Value
select user;
DropDownList2.DataSource = query;
DropDownList2.DataBind();
}
but I am unable to populate the states in another DDL can anyone help me with this?
Upvotes: 1
Views: 239
Reputation: 63065
I have changed your query as:
var query = from user in main.Root.Descendants("country")
where user.Elements("state").Any() && user.Elements("state").First().Value == st
select user;
please note, I took the descendants of Root elements and check for state element exist of country and then check the state value with given value. If match found that country element will be selected.
And also this will return XMlelements, you can't directly bind them to DataSource
, from that query you can select country name and something and finally convert it to a list or array. the result of above can directly bind to a DropDownList
here is sample xml:
<?xml version="1.0" encoding="utf-8" ?>
<countries>
<country>Test1</country>
<country name ="A">
<state>Test2</state>
</country>
<country name ="B">
<state>Test2</state>
</country>
<country name ="C">
<state>Test3</state>
</country>
</countries>
load the xml
XDocument main = XDocument.Load("input.xml");
Get country Names from from country element attribute
var countryNames = (from user in main.Root.Descendants("country")
where user.Elements("state").Any() && user.Elements("state").First().Value == "Test2"
select user.Attribute("name").Value).ToList();
your XML:
<country>
<name>India</name>
<state>
<text>Maharashtra</text>
<text>Kashmir</text>
<text>Goa</text>
</state>
</country>
updated code:
var countryNames = (from user in main.Descendants("country")
where user.Elements("state").Descendants("text").Any(s => s.Value == st)
select user.Element("name").Value).ToList();
Upvotes: 1
Reputation: 2954
use this instead:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string st = DropDownList1.SelectedValue;
XDocument main = XDocument.Load((Server.MapPath(@"XMLFile1.xml")));
var query = from user in main.Descendants("country")
where st == user.Element("state").Value
select user;
DropDownList2.DataSource = query;
DropDownList2.DataBind();
}
You were using the index (1/2/3/4/5) of the item, not the value, I changed it so that you use the value (display member) rather than the index of that item.
Upvotes: 0