Recently I encounter question at the forums.asp.net asking if how to move selected ListItems from one CheckBoxList to another. So I decided to post the solution that I have provided in that thread so that others can refer this post if they will encounter the same thing.
Here’s the code block below:
ASPX:
<table>
<tr>
<td>
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem>Player1</asp:ListItem>
<asp:ListItem>Player2</asp:ListItem>
<asp:ListItem>Player3</asp:ListItem>
<asp:ListItem>Player4</asp:ListItem>
<asp:ListItem>Player5</asp:ListItem>
<asp:ListItem>Player6</asp:ListItem>
</asp:CheckBoxList>
</td>
<td>
<asp:Button ID="ButtonAdd" runat="server" Text=">>"
onclick="ButtonAdd_Click" />
<br />
<asp:Button ID="ButtonRemove" runat="server"
Text="<<" onclick="ButtonRemove_Click" />
</td>
<td>
<asp:CheckBoxList ID="CheckBoxList2" runat="server">
</asp:CheckBoxList>
</td>
</tr>
</table>
RELEVANT CODES:
protected void ButtonAdd_Click(object sender, EventArgs e){
for (int i = CheckBoxList1.Items.Count - 1; i >= 0; i--)
{
if (CheckBoxList1.Items[i].Selected)
{
CheckBoxList2.Items.Add(CheckBoxList1.Items[i]);
CheckBoxList2.ClearSelection();
CheckBoxList1.Items.Remove(CheckBoxList1.Items[i]);
}
}
}
protected void ButtonRemove_Click(object sender, EventArgs e){
for (int i = CheckBoxList2.Items.Count - 1; i >= 0; i--)
{
if (CheckBoxList2.Items[i].Selected)
{
CheckBoxList1.Items.Add(CheckBoxList2.Items[i]);
CheckBoxList1.ClearSelection();
CheckBoxList2.Items.Remove(CheckBoxList2.Items[i]);
}
}
}
That's it! I hope someone find this post useful!
Technorati Tags:
ASP.NET,
C#