通过读取XML文档数据,实现省市区联动,主要方便个人快速使用,仅做参考~
添加三个ComboBox:cbx_Province、cbx_City、cbx_CityArea,代码如下:
using System; using System.Collections.Generic; using System.Windows.Forms; using System.Xml; namespace ApplicationOne { public partial class Form1 : Form { XmlDocument doc = new XmlDocument(); List<string> ListString = new List<string>(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { try { doc.Load("http://files.cnblogs.com/Interkey/%E7%9C%81%E5%B8%82%E5%8C%BA.xml"); XmlNode provinces = doc.SelectSingleNode("/ProvinceCity"); //本文地址:http://www.cnblogs.com/Interkey/p/3512910.html cbx_Province.Items.Clear(); foreach (XmlNode province in provinces.ChildNodes) { cbx_Province.Items.Add(province.Name); } if (cbx_Province.Items.Count >= 0) { cbx_Province.SelectedIndex = 0; } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void cbx_Province_SelectedIndexChanged(object sender, EventArgs e) { this.cbx_City.Items.Clear(); string xpath = string.Format("/ProvinceCity/{0}/City", cbx_Province.SelectedItem.ToString()); XmlNodeList cities = doc.SelectNodes(xpath); //本文地址:http://www.cnblogs.com/Interkey/p/3512910.html foreach (XmlNode city in cities) { cbx_City.Items.Add(city.Attributes["Name"].Value); } if (cbx_City.Items.Count >= 0) { cbx_City.SelectedIndex = 0; } } private void cbx_City_SelectedIndexChanged(object sender, EventArgs e) { cbx_CityArea.Items.Clear(); string xpath = string.Format("/ProvinceCity/{0}/City[@Name=‘{1}‘]/CityArea", cbx_Province.SelectedItem.ToString(), cbx_City.SelectedItem.ToString()); XmlNodeList CityAreas = doc.SelectNodes(xpath); //本文地址: http://www.cnblogs.com/Interkey/p/3512910.html foreach (XmlNode area in CityAreas) { cbx_CityArea.Items.Add(area.Attributes["Name"].Value); } if (cbx_CityArea.Items.Count >= 0) { cbx_CityArea.SelectedIndex = 1; } } } }
效果图:
XML地址:http://files.cnblogs.com/Interkey/%E7%9C%81%E5%B8%82%E5%8C%BA.xml
本文参考了以下内容:
省市区三联动的winform程序