2012-04-19 83 views
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' 不包含屬性的名稱'國家'。

回答

1

將其綁定到country_text

DropDownListCountry.DataTextField = "country_text"; 

您的數據集的三個表。國家,州和文本。數據集中保存國家/地區值的字段爲country_text,這就是你應該綁定的內容

+0

它正在工作,但是在獲取此錯誤時找不到文件C:\ Program Files \ Common Files \ Microsoft Shared \ DevServer \ 10.0 \ XMLFile.xml」。 ' – Krunal 2012-04-19 09:01:54

+0

因爲在selectedindexchanged事件中你沒有使用Server.MapPath(「state.xml」)。使用Server.MapPath無論你正在加載XMLFile – Habib 2012-04-19 09:06:37

+0

我試過這個,'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