C#用ComboBox控件实现省与市的联动效果的方法

本文实例讲述了C#用ComboBox控件实现省与市的联动效果的方法。分享给大家供大家参考。具体实现方法如下:

代码如下:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Data.SqlClient; 
using System.Configuration; 
 
namespace 省市联动 

    public partial class Form1 : Form 
    { 
        public Form1() 
        { 
            InitializeComponent(); 
        } 
 
        private void Form1_Load(object sender, EventArgs e) 
        { 
            Tsql.GetConnection(); 
            using (SqlConnection conn = new SqlConnection(Tsql.GetConnection())) 
            { 
                conn.Open(); 
                using (SqlCommand cmd = conn.CreateCommand()) 
                { 
                    cmd.CommandText = "select * from promary"; 
                    using (SqlDataReader dr = cmd.ExecuteReader()) 
                    { 
                        while (dr.Read()) 
                        { 
                            Province pr = new Province(); 
                            pr.proID = dr.GetInt32(dr.GetOrdinal("proID"));  //这里要特别注意数据库字段的类型 proID在数据库里是int型 
                            pr.proName = dr.GetString(dr.GetOrdinal("proName")); 
                            comboBox1.Items.Add(pr);//pr是一个Province对象。Province有一个proName和proID属性。我将一个对象填充到comboBox1里。再让comboBox1的DisplayMember属性设置proName。【也就是让comboBox1显示pr对象的proName属性】。这样在填充市级城市的时候我就可以找到当前选择项comboBox1.SelectedItem(或者当前选择对象)所对应的proID 
                        } 
                    } 
                } 
                comboBox1.SelectedIndex = 0;  //将comcomboBox1的默认选项设为0 
            } 
        } 
 
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) 
        { 
        } 
 
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
        { 
            comboBox2.Items.Clear(); //在选择的时候先清空一下combox1里面的所以项,以免在更换省名的时候,与先前对应的省名下的市没有删除。 
            Province tem = (Province)comboBox1.SelectedItem; // 因为在comboBox1.Items.Add(pr)里添加的是对象。所以在这里讲comBox1所选中的当前对象赋给tem对象 (tem对象下面有两个属性 proName和proID) 
             
            int id = tem.proID;  //将当前选中对象的的proID赋值给id,给下面的sql查询语句使用 
            Tsql.GetConnection();// 获取数据库连接字符串。 
            using (SqlConnection conn = new SqlConnection(Tsql.GetConnection())) 
            { 
                conn.Open(); 
                using (SqlCommand cmd = conn.CreateCommand()) 
                { 
                     
                    cmd.CommandText = "select * from city where proID=@id"; 
                    cmd.Parameters.Add(new SqlParameter("id", id)); 
                    using (SqlDataReader dr = cmd.ExecuteReader()) 
                    { 
                        while (dr.Read()) 
                        { 
                            comboBox2.Items.Add(dr.GetString(dr.GetOrdinal("cityName"))); 
                        } 
                    } 
                } 
                comboBox2.SelectedIndex = 0; //将comcomboBox1的默认选项设为0 
            } 
        } 
    } 
    class Tsql 
    { 
        public static string GetConnection() //数据库连接字符串 
        { 
            string getConn = ConfigurationManager.ConnectionStrings["getConn"].ConnectionString; 
            return getConn; 
        }        
    } 
    class Province 
    { 
        public string proName { get; set; } 
        public int proID { get; set; } 
    } 
}

代码如下:

using System.Data.SqlClient;
namespace 省市选择2
{
    public partial class Form1 : Form
    {
        publicForm1()
        {
            InitializeComponent();
        }
        privatevoid Form1_Load(objectsender,EventArgs e)
        {
            /*
            //测试代码:执行这段代码的情况下是可以吧 tom这个值添加到 comboBox1中的。
            People p1 = new People();
            p1.name = "tom";
            p1.age = 25;
            comboBox1.Items.Add(p1.name);
            */
            using(SqlConnection conn =newSqlConnection("Data source=凡斌-VAIO;Initialcatalog=DBPromary;integrated security=true"))
            {
                conn.Open();
                using(SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "select * from promary";
                    using(SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            //string str =reader.GetString(reader.GetOrdinal("proName"));
                            //comboBox1.Items.Add(str);
                            Province  pv =new  Province();
                            //将comboBox1控件的DisplayMember属性设置为“ProvinceName”用来在comboBox1控件中显示ProvinceName属性的值
                           comboBox1.DisplayMember = "ProvinceName";
                            pv.ProvinceName =reader.GetString(reader.GetOrdinal("proName"));
                            pv.ProvinceID =reader.GetInt32(reader.GetOrdinal("proID"));
                            //虽然pv属于对象,把一个对象添加到ComboxBox1中,控件显示的值为对象的类名,但是在前面comboBox1.DisplayMember ="ProvinceName"处已经设置好控件要显示的为 Province类的ProvinceName值,所以添加进去的是pv对象的ProvinceName值
                            comboBox1.Items.Add(pv);
                        }                     
                    }
                }
            }
        }
 
        privatevoid comboBox1_SelectedIndexChanged(object sender,EventArgse)       //注意这里是comboBox1不是comboBox2
        {
            try
            {
                Province  tem = (Province) comboBox1.SelectedItem;
                int id = tem.ProvinceID;
 
                comboBox2.Items.Clear();
                using(SqlConnection conn =newSqlConnection("Data source=凡斌-VAIO;Initialcatalog=DBPromary;integrated security=true"))
                {
                    conn.Open();
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        //查询city(市)表里的 proID与promary(省)表里proID相同的所有数据。
                        cmd.CommandText = "select * from city where proID =@id";
                        cmd.Parameters.Add(new SqlParameter("id", id));
                        SqlDataReader dr = cmd.ExecuteReader();
 
                        while(dr.Read())
                        {
                           comboBox2.Items.Add(dr.GetString(dr.GetOrdinal("cityName")));
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("错误信息:" + ex.Message);
            }
        }
    }
  
    class Province
    {
        public string ProvinceName { get;set; }
        public int ProvinceID { get;set; }
    }
    //class People
    //{
    //   public string name { get; set; }
    //   public int age { get; set; }
    //}
}

如下图所示:

希望本文所述对大家的C#程序设计有所帮助。

(0)

相关推荐

  • jQuery EasyUI API 中文文档 - ComboBox组合框

    扩展自 $.fn.combo.defaults. 用 $.fn.combobox.defaults 重写了 defaults. 依赖 combo 用法 <select id="cc" name="dept" style="width:200px;"> <option value="aa">aitem1</option> <option>bitem2</option>

  • C#实现ComboBox自动匹配字符

    1. 采用CustomSource当做提示集合 将下列代码添加到窗口加载函数中即可.假设unitNameList是获取的想要添加到下拉列表中的字符串列表. 复制代码 代码如下: AutoCompleteStringCollection collection = new AutoCompleteStringCollection(); // 获取单位列表 List<string> unitNameList = this.getAllUnitName(); foreach (string unitn

  • C# 重写ComboBox实现下拉任意组件的方法

    一.需求 C#种的下拉框ComboBox不支持下拉复选框列表与下拉树形列表等,系统中需要用到的地方使用了第三方组件,现在需要将第三方组件替换掉. 二.设计 基本思路:重写ComboBox,将原生的下拉部分屏蔽,使用toolStripDropDown制作下拉弹出 三.问题解决 1. 问题:toolStripDropDown中放toolStripControlHost时会有边框产生,同时CheckedListBox的duck为full时底端会有很大空白 解决: toolStripControlHos

  • C#实现带搜索功能的ComboBox

    带搜索的ComboBox就是给ComboBox一个依赖属性的ItemSource,然后通过数据源中是否包含要查询的值,重新给ComboBox绑定数据源. public class EditComboBox : ComboBox { private bool t = true;//首次获取焦点标志位 private ObservableCollection<object> bindingList = new ObservableCollection<object>();//数据源绑定

  • C#实现绑定Combobox的方法

    本文实例讲述了C#实现绑定Combobox的方法.分享给大家供大家参考.具体实现方法如下: public class StaticVariable { public Dictionary<string, string> tabTypeArray; public Dictionary<string, string> transTimeArray; public Dictionary<string, string> fileDealTypeArray; public Sta

  • C# ComboBox的联动操作(三层架构)

    项目需求:根据年级下拉框的变化使得科目下拉框绑定次年级下对应有的值 我们用三层架构的模式来实现 1.我们想和数据库交互,我们首先得来先解决DAL数据库交互层 01.获得年级下拉框的数据 在GradeDAL类中 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient;

  • C# listview添加combobox到单元格的实现代码

    实现代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplicat

  • C#(WinForm) ComboBox和ListBox添加项及设置默认选择项

    Web控件DropDownList和WinForm控件ComboBox机制不一样. ComboBox没有对应的ListItem需要自己写一个: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WinListItem { /// <summary> /// 选择项类,用于ComboBox或者ListBox添加项 /// </summary>

  • c#构造ColorComboBox(颜色下拉框)

    复制代码 代码如下: class ColorComboBox : ComboBox    {        /// <summary>        /// 当前选中色        /// </summary>        public Color SelectedColor        {            get { return Color.FromName(this.Text); }        }        /// <summary>     

  • C#实现ComboBox控件显示出多个数据源属性的方法

    本文实例讲述了C#实现ComboBox控件显示出多个数据源属性的方法.分享给大家供大家参考.具体如下: public partial class Form4 : Form { private Bitmap myBitmap; public Form4() { InitializeComponent(); DataTable dt = new DataTable(); DataColumn dc1 = new DataColumn("Name", typeof(System.String

随机推荐