zoukankan      html  css  js  c++  java
  • 实现dropDownList listBox联动

    在listBox中显示dropDownList中选定的部门

    一 SQL SERVER建立两张表
       1 建立数据库department
       2 在department中建立两张表:部门表 TDepartment(depID,depName)
                                   员工表 emp(empID,empName,depID)

    二 在VS下新建Web页
       1 拖入一个dropDownList和一个listBox,分别改名为ddlDep,lBoxEmp
       2 首先把数据库中的部门显示在dropDownList中
         2.1 添加数据库连接类 DB.cs
             using System;
             using System.Data.SqlClient;
             public class DB
             {
          public DB()
          {}
                 public static SqlConnection createCon()
                 {
                      return new SqlConnection("server=.;database=adoNetTest;uid=huan;pwd=1234567890");
                 }
             }

         2.2 编写Page_Load方法
             if(!this.IsPostBack)   
             {
                 SqlConnection con=DB.createCon();
                 con.Open();
                 SqlCommand cmd=new Sqlcommand("Select * from TDeparment");
                 SqlDataReader sdr=cmd.ExecuteReader();
                 this.ddlDep.DataSource=sdr;           //数据源
                 this.ddlDep.DataTextField="depName";  //指定要显示的列名
                 this.ddlDep.DataValueField="depID";  //主键
                 this.ddlDep.DataBind();              //绑定
                 sdr.Close();
             }
      3  在listBox中显示对应部门的员工
           3.1  sdr.Close();之后继续编写
              SqlCommand cmdEmp=new Sqlcommand("Select * from emp where depID="+this.ddlDep.SelectedValue,con);
              SqlDataReader sdrEmp=cmdEmp.ExecuteReader();
              while(sdrEmp.Read())
              {
                   this.lBoxEmp.Items.Add(new ListItem(sdrEmp.GetString(1),sdrEmp.gETiNT32(0).ToString()));
              }
              sdrEmp.Close();
         
          3.2 修改ddlDep的AutoPostBack属性为true
              编写事件SelectedIndexChanged双击即可,添加如下代码
              this.lBoxEmp.Items.Clear();
              SqlConnection con=DB.createCon();
              con.Open();
              SqlCommand cmdEmp=new Sqlcommand("Select * from emp where depID="+this.ddlDep.SelectedValue,con);
              SqlDataReader sdrEmp=cmdEmp.ExecuteReader();
              while(sdrEmp.Read())
              {
                   this.lBoxEmp.Items.Add(new ListItem(sdrEmp.GetString(1),sdrEmp.gETiNT32(0).ToString()));
              }
              sdrEmp.Close();
              con.Close();
      4 关闭连接
              con.Close();

  • 相关阅读:
    索引的优缺点
    php中创建和调用WebService
    Redis常用数据结构和操作
    PHP的array_merge
    数据库最左前缀原则
    Mysql+Sphinx实现全文搜索
    YAPI安装和使用
    根据导入xlxs的文件,来写入数据库
    操作RDS文档说明
    springboot查找配置文件路径的过程
  • 原文地址:https://www.cnblogs.com/chenlong/p/1590743.html
Copyright © 2011-2022 走看看