【发布时间】:2012-04-30 19:17:43
【问题描述】:
我是 ASP.NET 的新手,
我正在制作国家,州下拉列表。
例如:对于特定国家/地区,我将从 XML 文件中读取该国家/地区的状态。
我无法在下拉列表中获取所需国家/地区的状态...
这是我在XMLFile.xml中的代码sn-p
<?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>
和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();
}
}
错误: 对象引用未设置为对象的实例。
提前致谢!
【问题讨论】:
-
你在哪一行得到错误
-
我的 linq
query给了我空值.. 你能检查一下... -
a) 您的 xml 中没有名称为
"country_text"的元素 b) 您的州不在 country 元素内.. c)"state"没有价值,但"text"在州内有价值..请在使用之前正确修改您的xml -
您的 xml 文档并不暗示一个国家与其下属的州之间的关系。也许像
<country name="country1"><state name="state1"/><state name="state2"/></country>这样的结构更适合 -
我按照你的建议编写了我的 xnl 文件,并尝试了这个查询,但我仍然没有得到 o/p: var query = from user in doc.Descendants("state") where st == user .Element("state").Value select user.NextNode;
标签: asp.net xml linq drop-down-menu data-binding