Three-level linkage-Query the region, select the province to automatically show the province's cities, counties
Like the next database
First, write the Query method
Public classChinadata {SqlConnection conn=NULL; SqlCommand cmd=NULL; PublicChinadata () {conn=NewSqlConnection ("server=.; Database=mydb;user=sa;pwd=123"); CMD=Conn. CreateCommand (); } //Query method parameters are parent code PublicList<china> Select (stringPcode) {List<China> LC =NewList<china>(); Cmd.commandtext="Select *from chinastates where [email protected]"; Cmd. Parameters.clear (); Cmd. Parameters.addwithvalue ("@a", Pcode); Conn. Open (); SqlDataReader Dr=cmd. ExecuteReader (); if(Dr. HasRows) { while(Dr. Read ()) {China C=NewChina (); C.areacode= dr["AreaCode"]. ToString (); C.areaname= dr["AreaName"]. ToString (); C.parentareacode= dr["Parentareacode"]. ToString (); Lc. ADD (c); }} conn. Close (); returnLC; } }
Query Method
Second, automatically read the database data when the form starts
Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); //when the window opens, automatic query Code 0001 sub-level data in China//Binding ProvinceCombobox1.datasource =NewChinadata (). Select ("0001"); Combobox1.displaymember="AreaName"; Combobox1.valuemember="AreaCode"; //Binding CityCombobox2.datasource =NewChinadata (). Select (ComboBox1.SelectedValue.ToString ()); Combobox2.displaymember="AreaName"; Combobox2.valuemember="AreaCode"; //Bound CountiesCombobox3.datasource =NewChinadata (). Select (ComboBox2.SelectedValue.ToString ()); Combobox3.displaymember="AreaName"; Combobox3.valuemember="AreaCode"; } }
automatically read database data when form starts
Third, the implementation of change options, the presentation of sub-level content
//event When selected item is changed by province Private voidComboBox1_SelectedIndexChanged (Objectsender, EventArgs e) { //Binding CityCombobox2.datasource =NewChinadata (). Select (ComboBox1.SelectedValue.ToString ()); Combobox2.displaymember="AreaName"; Combobox2.valuemember="AreaCode"; } //event when the city selection changes Private voidCombobox2_selectedindexchanged_1 (Objectsender, EventArgs e) { //Bound CountiesCombobox3.datasource =NewChinadata (). Select (ComboBox2.SelectedValue.ToString ()); Combobox3.displaymember="AreaName"; Combobox3.valuemember="AreaCode"; }
achieve two-level linkage, three-level linkage
Complete Regional selection
c#-winform-three-level linkage