您的位置:首页 > 运维架构

转载---使用Ajax实现DropDownList和ListBox的联动以及两个ListBox之间数据的移动

2008-06-12 11:29 936 查看
最近做一个项目管理系统,有一个项目添加中使用到,需要选择部门然后得到部门的职员,还要选择这个部门中有哪些人需要参与这个项目,所以就使用到了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> 

</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 窗体设计器生成的代码

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(',')即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: