Use Ajax to implement the association between DropDownList and ListBox and the movement of data between two listboxes

Source: Internet
Author: User
Recently, a project management system was created, and a project was added for use. You need to select a department and then get the Department staff. You also need to select who needs to participate in the project, therefore, three controls are used, one DropDownList and two listboxes.
In the blog and CSDN, I often see some articles about Ajax technology, and I learned a little about it. So I simply used it here. I hope you will not laugh at it.
At the beginning, The ListBox on the left shows all employees of the company, while the DropDownList shows departments. The bottom TextBox is used to store the ID of the selected employee, separated by commas.

Two tables are used: department table and employee table. The SQL script is as follows:
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

Front-end code:

<% @ 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.txt EmpID. 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"> company: </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"> project member: </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"> store the value in the listNew control: </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 = "OK" CssClass = "redButtonCss" Height = "24"> </asp: button> & nbsp;
</TD>
</TR>
</Table>
</TD> </TR> </TABLE>
</Form>
</Body>
</HTML>
Background code:

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>
/// Summary of 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. etettings ["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 ();");
}
}

# Code generated by region Web Form Designer
Override protected void OnInit (EventArgs e)
{
//
// CODEGEN: This call is required by the ASP. NET Web form designer.
//
InitializeComponent ();
Base. OnInit (e );
}

/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
Private void InitializeComponent ()
{
This. btnSubmit. Click + = new System. EventHandler (this. btnSubmit_Click );
This. Load + = new System. EventHandler (this. Page_Load );

}
# Endregion

# Region obtain the Department
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 get all employees
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 );
}


}
}

I think everyone knows that AJAX is used to call methods in a class in javaScript. Therefore, the methods in AjaxMothod are as follows:

Using System;
Using System. Data. SqlClient;
Using System. Data;
Namespace NetTest. ListBoxTest
{
/// <Summary>
/// AjaxTest abstract description.
/// </Summary>
Public class AjaxMethod
{
Private string strConn = System. Configuration. ConfigurationSettings. etettings ["ConnectionString"]. ToString ();
Public AjaxMethod ()
{
//
// TODO: add the constructor logic here
//
}

# Region obtain Department employees by department ID
[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
}
}

There are also settings in webconfig
<HttpHandlers>
<Add verb = "POST, GET" path = "ajax/*. ashx" type = "Ajax. PageHandlerFactory, Ajax"/>
</HttpHandlers>
The preliminary use of these Ajax can refer to the Hill Blog (http://singlepine.cnblogs.com/articles/253393.html ).

Note that the JavaScript code used between two listboxes is related to the id of the <form> flag, because the <form> is not modified after a page is generated by a common user, so please note.
After selecting the developer of the project, we need to input the database, but what we do first must get the ID of the selected employee, therefore, we must first obtain the selected number before executing the Button_Click event. Therefore, register a client event in Page_Load, btnSubmit. attributes. add ("onclick", "GetData ();"); in this way, the number of the selected employee can be saved in TextBox, and txtEmpID is directly used in the code. text to get the value. If you need to Split, use Split.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.