导航

两个ListBox的互动方法

Posted on 2010-09-25 15:57  ykhi  阅读(696)  评论(0)    收藏  举报

来源:http://cfeng518.blog.163.com/blog/static/174677322007112011553642/

效果:


ASPX页面: 

<table>
<tbody>
<tr>
<td>
<asp:ListBox ID="lbLeft" runat="server" SelectionMode="Multiple">
<asp:ListItem>添加名字</asp:ListItem>
<asp:ListItem>出生年月</asp:ListItem>
</asp:ListBox>
</td>
<td style="width: 27px">
<asp:Button ID="btnToRight" runat="server" Text=">>"
OnClick
="btnToRight_Click" />
<br />
<asp:Button ID="btnToLeft" runat="server" Text="<<"
OnClick
="btnToLeft_Click" />
</td>
<td style="width: 3px">
<asp:ListBox ID="lbRight" runat="server"
SelectionMode
="Multiple"></asp:ListBox></td>
</tr>
</tbody>
</table>
<asp:Label ID="lblMsg" runat="server"></asp:Label>

CS Code :

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class Test1 : System.Web.UI.Page
{
protected void Page_Load ( object sender , EventArgs e )
{

}
protected void btnToRight_Click(object sender, EventArgs e)
{
if(lbLeft.SelectedItem != null)
{
AddItemFromSourceListBox(lbLeft, lbRight);

RemoveSelectedItem(lbLeft);

lblMsg.Text
=""; //注意:为什么要这一行?

foreach(ListItem item in lbRight.Items)
{
if(item.Selected)
lblMsg.Text
+=item.Text;
}
}
}

protected void btnToLeft_Click(object sender, EventArgs e)
{
if(lbRight.SelectedItem != null)
{
AddItemFromSourceListBox(lbRight, lbLeft);
RemoveSelectedItem(lbRight);
}
}

private void RemoveSelectedItem(ListBox listControl)
{
while(listControl.SelectedIndex != -1)
{
listControl.Items.RemoveAt(listControl.SelectedIndex);
}
}

private void AddItemFromSourceListBox(ListBox sourceBox,ListBox targetBox)
{
foreach(ListItem item in sourceBox.Items)
{
if(item.Selected == true && !targetBox.Items.Contains(item))
{
targetBox.Items.Add(item);
}
}
}

}