惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
有赞技术团队
有赞技术团队
T
The Blog of Author Tim Ferriss
F
Fortinet All Blogs
D
DataBreaches.Net
F
Full Disclosure
腾讯CDC
博客园 - 【当耐特】
MyScale Blog
MyScale Blog
Stack Overflow Blog
Stack Overflow Blog
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
爱范儿
爱范儿
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
大猫的无限游戏
大猫的无限游戏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
SegmentFault 最新的问题
The Register - Security
The Register - Security
WordPress大学
WordPress大学
博客园 - 聂微东
雷峰网
雷峰网
J
Java Code Geeks
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy International News Feed
酷 壳 – CoolShell
酷 壳 – CoolShell
A
Arctic Wolf
Scott Helme
Scott Helme
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tor Project blog
博客园 - 三生石上(FineUI控件)
Know Your Adversary
Know Your Adversary
AWS News Blog
AWS News Blog
G
Google Developers Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
C
CERT Recently Published Vulnerability Notes
O
OpenAI News
Project Zero
Project Zero
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Application and Cybersecurity Blog
Application and Cybersecurity Blog
云风的 BLOG
云风的 BLOG
N
News and Events Feed by Topic
MongoDB | Blog
MongoDB | Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Microsoft Security Blog
Microsoft Security Blog
Cisco Talos Blog
Cisco Talos Blog
P
Palo Alto Networks Blog
Schneier on Security
Schneier on Security

博客园 - 白天的萤火虫

Net开源框架/项目,你研究过几个? 主题:实用且不花哨的js代码大全 关于模拟注册登录的 字字带泪-写在三十岁到来这一天 关于silverlight的安装 推荐一个IE下的优秀js调试工具(Companion.JS) 给分页控件增加一列 编号 关于Ajax的web配置 - 白天的萤火虫 - 博客园 一个行转列的例子 获取HTML代码 - 白天的萤火虫 - 博客园 最新Silverlight开发环境配置介绍 sql server中的存储过程调试 PetShop介绍集锦 DIV+CSS实现圆角 button 绑定 enter键 自己调试通过的存储过程 又一个通用分页存储过程,支持表别名,多表联合查询SQL语句--转载 写入和读取cookie CascadingDropDown从数据库中读取数据绑定到DropDownList控件上
转载---使用Ajax实现DropDownList和ListBox的联动以及两个ListBox之间数据的移动
白天的萤火虫 · 2008-06-12 · via 博客园 - 白天的萤火虫
     最近做一个项目管理系统,有一个项目添加中使用到,需要选择部门然后得到部门的职员,还要选择这个部门中有哪些人需要参与这个项目,所以就使用到了3个控件,一个DropDownList和两个ListBox.
           在博客园和CSDN中经常会看到有人发Ajax技术的文章,学习了一些,所以在此也简单的使用了一下,希望大家不要见笑。
           一开始左边一个ListBox中显示的是公司的所有的员工,DropDownList则显示的是部门。最下面的一个TextBox是为了存储选中的职员的ID,多个之间使用逗号隔开的。

这里使用到了两张表:部门表和员工表   SQL脚本如下:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Emp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Emp]
GO

CREATE TABLE [dbo].[Emp] (
 [EmpID] [int] IDENTITY (1, 1) NOT NULL ,
 [EmpName] [varchar] (20) COLLATE Chinese_PRC_CI_AS NULL ,
 [Age] [int] NULL ,
 [Dept] [int] NULL ,
 [DelFlag] [bit] NULL
) ON [PRIMARY]
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Department]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Department]
GO

CREATE TABLE [dbo].[Department] (
 [DeptID] [int] IDENTITY (1, 1) NOT NULL ,
 [Name] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO

前台代码:

<%@ Page language="c#" Codebehind="ListBoxToListBox.aspx.cs" AutoEventWireup="false" Inherits="NetTest.ListBoxTest.ListBoxToListBox" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>ListBoxToListBox</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <link href="../CSS/BasicLayout.css" rel="stylesheet" type="text/css">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  <style type="text/css"> .fsize { FONT-SIZE: 10pt } </style>
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <script language="javascript">
  function BindListEmp()
  {
   var DeptID=document.getElementById("ddlDept").value;
   var obj=AjaxMethod.GetEmpByDeptID(DeptID);
   if(obj.value!=null)
   {
    document.all("listEmployees").length=0;
    var ds=obj.value;
    
    if(ds != null && typeof(ds) == "object" && ds.Tables != null)
    {
     for(var i=0; i<ds.Tables[0].Rows.length; i++)
       {
        var name=ds.Tables[0].Rows[i].EmpName;
         var id=ds.Tables[0].Rows[i].EmpID;
         //alert(name);
         //alert(id);
         document.all("listEmployees").options.add(new Option(name,id));
       }
    }
    else
    {
    }
   }
   else
   {
   }
  }
  </script>
  <script language="javascript"> 
   function GetData()
   {
    listNewEmp = eval("document.FrmListBox.listNewEmp");
    document.getElementById("txtEmpID").value="";
    for(i=0;i<listNewEmp.length;i++)
    {
     document.FrmListBox.txtEmpID.value+=listNewEmp.options[i].value+",";
    }
   }
   function AddItem(ControlName)
   {
    Control = null;
    Control=eval("document.FrmListBox.listNewEmp"); 
    var x=0;
    var i=0;
    var y=0;
    listEmployees=eval("document.FrmListBox.listEmployees");
    listNewEmp=eval("document.FrmListBox.listNewEmp");
    var j=listEmployees.length;
    
    for(i=0;i<j;i++)
    {
     if(listEmployees.options[i].selected==true)
     {
      //alert(Control.length);
         if(Control.length==0)
         {
       Control.add(new Option(listEmployees[i].text,listEmployees.options[i].value)); 
       listNewEmp=eval("document.FrmListBox.listNewEmp");
       continue;
         }
         else
         {
       for(x=0;x<listNewEmp.length;x++)
       {
        if(listEmployees.options[i].value==listNewEmp.options[x].value)
        {
         y++;
        }
        
       }
         }
         if(y==0)
         {
       Control.add(new Option(listEmployees[i].text,listEmployees.options[i].value));
       listNewEmp=eval("document.FrmListBox.listNewEmp");
         }
     }
    }
   }
   function RemoveItem(ControlName)
   {
    Control = null;
    Control=eval("document.FrmListBox.listNewEmp"); 
   
    var j=Control.length;
    if(j==0) return;
    for(j;j>0;j--)
    {
     if(Control.options[j-1].selected==true)
     {
       Control.remove(j-1);
     }
    }
       
   }
   
  </script>
  <form id="FrmListBox" method="post" runat="server">
   <table align="center" border="1" style="BORDER-COLLAPSE: collapse" borderColor="#ccccc"
    width="80%" class="fSize">
    <TR>
     <TD style="WIDTH: 191px" align="right" width="191" height="30">公司部门:</TD>
     <TD height="30"><asp:dropdownlist id="ddlDept" runat="server" Width="112px"></asp:dropdownlist></TD>
    </TR>
    <TR>
     <TD style="WIDTH: 191px" align="right" width="191" height="30">项目成员:</TD>
     <TD height="30">
      <TABLE id="Table3" cellSpacing="0" cellPadding="0" width="100%" border="0">
       <TR align="center">
        <TD style="WIDTH: 139px">
         <asp:listbox id="listEmployees" runat="server" Width="141" Height="160" SelectionMode="Multiple"></asp:listbox></TD>
        <TD style="WIDTH: 33px"><INPUT class="buttoncss" style="WIDTH: 48px; HEIGHT: 24px" onclick="AddItem(this.name)"
          type="button" value=">>>>" name="btnReceSendToRight"><BR>
         <INPUT class="buttoncss" style="WIDTH: 48px; HEIGHT: 24px" onclick="RemoveItem(this.name)"
          type="button" value="<<<<" name="btnReceSendToLeft">
        </TD>
        <TD align="left">
         <asp:listbox id="listNewEmp" runat="server" Width="141" Height="160" SelectionMode="Multiple"></asp:listbox>&nbsp;
        </TD>
       </TR>
      </TABLE>
     </TD>
    </TR>
    <tr>
     <td height="30" align="right">存储listNew控件中所得到的值:</td>
     <td>
      <asp:TextBox id="txtEmpID" runat="server"></asp:TextBox></td>
    </tr>
    <TR>
     <TD align="center" colSpan="2" height="35">&nbsp;
      <asp:button id="btnSubmit" runat="server" Width="64" Text="确定" CssClass="redButtonCss" Height="24"></asp:button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
     </TD>
    </TR>
   </table>
   </TD></TR></TABLE>
  </form>
 </body>
</HTML>

后台代码:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using Ajax;
namespace NetTest.ListBoxTest
{
 /// <summary>
 /// ListBoxToListBox 的摘要说明。
 /// </summary>
 public class ListBoxToListBox : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DropDownList ddlDept;
  protected System.Web.UI.WebControls.Button btnSubmit;
  protected System.Web.UI.WebControls.ListBox listEmployees;
  protected System.Web.UI.WebControls.ListBox listNewEmp;
  protected System.Web.UI.WebControls.TextBox txtEmpID;
  private string strConn=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"].ToString();
  
  private void Page_Load(object sender, System.EventArgs e)
  {
   Ajax.Utility.RegisterTypeForAjax(typeof(NetTest.ListBoxTest.AjaxMethod));

   if(!IsPostBack)
   {
    GetDepartment();
    GetEmployees();
    btnSubmit.Attributes.Add("onclick","GetData();");
   }
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  #region 得到部门
  private void GetDepartment()
  {
   SqlConnection Conn=new SqlConnection(strConn);
   SqlCommand Cmd=new SqlCommand("Select * from Department",Conn);
   SqlDataAdapter da=new SqlDataAdapter();
   da.SelectCommand=Cmd;
   DataSet ds=new DataSet();
   Conn.Open();
   da.Fill(ds);
   Conn.Close();
   ddlDept.DataSource=ds.Tables[0].DefaultView;
   ddlDept.DataTextField="Name";
   ddlDept.DataValueField="DeptID";
   ddlDept.DataBind();
   ddlDept.Attributes.Add("onChange","BindListEmp()");
  }
  #endregion

  #region 得到所有的员工
  private void GetEmployees()
  {
   SqlConnection Conn=new SqlConnection(strConn);
   SqlCommand Cmd=new SqlCommand("Select * from Emp",Conn);
   SqlDataAdapter da=new SqlDataAdapter();
   da.SelectCommand=Cmd;
   DataSet ds=new DataSet();
   Conn.Open();
   da.Fill(ds);
   Conn.Close();
   listEmployees.DataSource=ds.Tables[0].DefaultView;
   listEmployees.DataTextField="EmpName";
   listEmployees.DataValueField="EmpID";
   listEmployees.DataBind();
  }
  #endregion

  private void btnSubmit_Click(object sender, System.EventArgs e)
  {
   Response.Write(txtEmpID.Text);
  } 

  
 }
}

我想大家都知道使用AJAX技术,都是在javaScript中调用一个类里的方法,因此AjaxMothod中的方法如下

using System;
using System.Data.SqlClient;
using System.Data;
namespace NetTest.ListBoxTest
{
 /// <summary>
 /// AjaxTest 的摘要说明。
 /// </summary>
 public class AjaxMethod
 {
  private string strConn=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"].ToString();
  public AjaxMethod()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
  }

  #region 根据部门编号得到部门员工
  [Ajax.AjaxMethod]
  public DataSet GetEmpByDeptID(string DeptID)
  {
   try
   {
    int IntDeptID=int.Parse(DeptID);
    SqlConnection Conn=new SqlConnection(strConn);
    SqlCommand Cmd=new SqlCommand("Select * from Emp where Dept="+IntDeptID,Conn);
    SqlDataAdapter da=new SqlDataAdapter();
    da.SelectCommand=Cmd;
    DataSet ds=new DataSet();
    Conn.Open();
    da.Fill(ds);
    Conn.Close();
    return ds;
   }
   catch(Exception ex)
   {
    string str=ex.Message;
    return null;
   }
  }
  #endregion
 }
}

还有webconfig中的设置
<httpHandlers>
  <add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
   </httpHandlers> 
这些Ajax的初步使用可以参考一下小山的Blog(http://singlepine.cnblogs.com/articles/253393.html)。
       注意一下关于两个ListBox之间所使用到的JavaScript代码和<form>标记的id有关,因为一般人生成一个页面之后,都不会去修改<form>的,所以特别提醒一下。
       当我们选择好项目的开发人员之后,就需要进行数据库的录入操作了,但是第一步我们做的必须得到选中的职员的ID,所以在我们进行Button_Click事件之前,必须先得到选中的编号,所以在Page_Load中注册一个客户端的事件,btnSubmit.Attributes.Add("onclick","GetData();");这样选中的职员的编号就可以保存在TextBox,直接在代码里使用txtEmpID.Text得到值,如果需要分割,则使用Split(',')即可。