列表框 HTML代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <table width="600" border="1" cellspacing="0" cellpadding="0"> <tr> <td width="250" rowspan="4"> <asp:ListBox ID="ListBox1" runat="server" Height="300px" SelectionMode="Multiple" Width="243px"></asp:ListBox> </td> <td width="100" height="100"> </td> <td width="250" rowspan="4"> <asp:ListBox ID="ListBox2" runat="server" Height="300px" SelectionMode="Multiple" Width="243px"></asp:ListBox> </td> </tr> <tr> <td height="50"> <asp:Button ID="Button1" runat="server" Height="36px" OnClick="Button1_Click" Text="->" Width="82px" /> </td> </tr> <tr> <td height="50"> <asp:Button ID="Button2" runat="server" Height="39px" OnClick="Button2_Click" Text=">>" Width="80px" /> </td> </tr> <tr> <td height="100"> </td> </tr> </table> </div> </form> </body> </html>
列表框 后台C#代码
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { TestDataContext context = new TestDataContext(); ListBox1.DataSource = context.Nation; ListBox1.DataTextField = "Name"; ListBox1.DataValueField = "Code"; ListBox1.DataBind(); } } protected void Button1_Click(object sender, EventArgs e) { //找选中项 foreach (ListItem item in ListBox1.Items) { if (item.Selected) { if (!ListBox2.Items.Contains(item)) { ListBox2.Items.Add(item); } } } } protected void Button2_Click(object sender, EventArgs e) { foreach (ListItem item in ListBox1.Items) { if (!ListBox2.Items.Contains(item)) { ListBox2.Items.Add(item); } } } }
时间: 2024-12-15 01:53:38