这是代码参考一下,另有附件.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace XMLDemo2
{
public partial class Form1 : Form
{
XmlDocument doc = new XmlDocument();
public Form1()
{
InitializeComponent();
doc.Load("省市区.xml");
XmlNode provinces = doc.SelectSingleNode("/ProvinceCity");
foreach (XmlNode province in provinces.ChildNodes) {
cbxProvince.Items.Add(province.Name);
}
cbxProvince.SelectedIndex = 0;
}
private void cbxProvince_SelectedIndexChanged(object sender, EventArgs e)
{
cbxCity.Items.Clear();
string xpath = string.Format("/ProvinceCity/{0}/City", cbxProvince.SelectedItem.ToString());
XmlNodeList cities = doc.SelectNodes(xpath);
foreach (XmlNode city in cities) {
cbxCity.Items.Add(city.Attributes["Name"].Value);
}
if(cbxCity.Items.Count >= 0) {
cbxCity.SelectedIndex = 0;
}
}
private void cbxCity_SelectedIndexChanged(object sender, EventArgs e)
{
cbxCityArea.Items.Clear();
string xpath = string.Format("/ProvinceCity/{0}/City[@Name='{1}']/CityArea",
cbxProvince.SelectedItem.ToString(),
cbxCity.SelectedItem.ToString());
XmlNodeList CityAreas = doc.SelectNodes(xpath);
foreach (XmlNode area in CityAreas) {
cbxCityArea.Items.Add(area.Attributes["Name"].Value);
}
if(cbxCityArea.Items.Count > 0) {
cbxCityArea.SelectedIndex = 0;
}
}
}
}
发的太乱,下拉列表联动很简单,使用IndexChanged事件就搞定。