這裡使用到了兩張表:部門表和員工表 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> </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"> <asp:button id="btnSubmit" runat="server" Width="64" Text="確定" CssClass="redButtonCss" Height="24"></asp:button> </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 Form設計器產生的程式碼 override protected void OnInit(EventArgs e) { // // CODEGEN: 該調用是 ASP.NET Web Form設計器所必需的。 // 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(',')即可。 |