从一个listbox添加到另一个Listbox,从一个listbox删除现有项:
///绑定listbox
void Bind_ListBoxDepart(ListBox lb)
{
dtDepart = clsDepart.GetTable(1);
lbDepart.DataTextField = "DEPARTNAME";
lbDepart.DataValueField = "DEPARTNO";
lbDepart.DataSource = dtDepart;
lbDepart.DataBind();
}
/// <summary>
/// 添加部门
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnAddDepart_Click(object sender, EventArgs e)
{
foreach (ListItem li in lbDepart.Items)
{
if (li.Selected)
{
txtDepart.Items.Add(new ListItem(li.Text.Trim(),li.Value.Trim()));
}
}
}
/// <summary>
/// 添加所有部门
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnAddAll_Click(object sender, EventArgs e)
{
foreach (ListItem li in lbDepart.Items)
{
txtDepart.Items.Add(new ListItem(li.Text, li.Value));
}
}
/// <summary>
/// 移去部门
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnDeleteDepart_Click(object sender, EventArgs e)
{
while (txtDepart.SelectedIndex != -1)
{
txtDepart.Items.Remove(txtDepart.SelectedItem);
}
}
/// <summary>
/// 移去所有部门
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnDeleteAll_Click(object sender, EventArgs e)
{
txtDepart.Items.Clear();
}
前台
<tr style="height: 27px;">
<td style="text-align: right; width: 100px">
添加部门
</td>
<td style="height: 100px">
<asp:ListBox ID="lbDepart" runat="server" SelectionMode="Multiple" Width="100px" Height="200px"></asp:ListBox>
</td>
<td style="text-align: center">
<asp:Button ID="btnAddDepart" runat="server" Text="添加" OnClick="btnAddDepart_Click" /><br />
<asp:Button ID="btnAddAll" runat="server" Text="全部添加" OnClick="btnAddAll_Click" /><br />
<asp:Button ID="btnDeleteDepart" runat="server" Text="删除" OnClick="btnDeleteDepart_Click" /><br />
<asp:Button ID="btnDeleteAll" runat="server" Text="全部删除" OnClick="btnDeleteAll_Click" />
</td>
<td style="height: 200px">
<asp:ListBox ID="txtDepart" Height="200px" runat="server" SelectionMode="Multiple" Width="100px"></asp:ListBox>
</td>
</tr>