用c#写个省市区三联动的winform程序,从xml文件中读取数据。数据用三个下拉显示

Xml的下载地址:http://pan.baidu.com/share/link?shareid=2260665311&uk=1176049979
2024-11-08 04:32:50
有2个网友回答
网友(1):

这是代码参考一下,另有附件.

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;
            }
        }
    }
}


网友(2):

发的太乱,下拉列表联动很简单,使用IndexChanged事件就搞定。