省市区联动小功能
通过读取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("https://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地址:https://files.cnblogs.com/Interkey/%E7%9C%81%E5%B8%82%E5%8C%BA.xml
本文参考了以下内容:
省市区三联动的winform程序
作者:Cosmic_Spy
出处:http://www.cnblogs.com/Interkey/
有兴趣可以加群【.NET破解|反编译】请注明:博客园,谢谢~
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则肯定是你抄我的。
posted on 2014-01-09 23:17 Cosmic_Spy 阅读(709) 评论(0) 编辑 收藏 举报