0
我是ASP.NET新手,使用XML绑定下拉列表
我在制作国家,州下拉列表。
例如:对于特定的国家,我将从XML文件中读取该国家的状态。
这里是XMLFile.xml
<?xml version="1.0" encoding="utf-8" ?>
<countrys>
<country>India</country>
<state>
<text>Maharashtra</text>
<text>Kashmir</text>
<text>Goa</text>
</state>
<country>Sri Lanka</country>
<state>
<text>Kanady</text>
<text>Colombo</text>
<text>Galle</text>
</state>
<country>Australia</country>
<state>
<text>Sydney</text>
<text>Perth</text>
<text>Melbourne</text>
</state>
<country>South Africa</country>
<state>
<text>Capetown</text>
<text>Johanusburg</text>
<text>Durban</text>
</state>
</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";
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 user in main.Descendants("country_text")
where st == user.Element("state").Value
select user;
DropDownListState.DataSource = query;
DropDownListState.DataBind();
}
}
错误:数据绑定: 'System.Data.DataRowView' 不包含属性的名称'国家'。
它正在工作,但是在获取此错误时找不到文件C:\ Program Files \ Common Files \ Microsoft Shared \ DevServer \ 10.0 \ XMLFile.xml”。 ' – Krunal 2012-04-19 09:01:54
因为在selectedindexchanged事件中你没有使用Server.MapPath(“state.xml”)。使用Server.MapPath无论你正在加载XMLFile – Habib 2012-04-19 09:06:37
我试过这个,'DataSet ds = new DataSet(); ds.ReadXml(Server.MapPath(“XMLFile.xml”)); var query = from ds.Descendants(“country_text”) where st == user.Element(“state”)。Value select user; DropDownListState.DataSource = query; DropDownListState.DataBind();' – Krunal 2012-04-19 09:10:07