在 Web Forms 中實作兩個 ListBox 之間透過按鈕移動項目(單向、雙向、全選)是常見需求。本文提供完整的 ASPX 標記與後端邏輯,可直接套用專案。
左右各一個 ListBox,中間放置四個按鈕:<< (全移左)、< (移左)、> (移右)、>> (全移右):
<div style="width:200px; float:left;">
<table>
<tr>
<td width="50%">
<asp:ListBox ID="ListBox2" runat="server" Height="128px" Width="148px">
<asp:ListItem Value="張三" />
<asp:ListItem Value="李四" />
<asp:ListItem>王五</asp:ListItem>
</asp:ListBox>
</td>
<td>
<asp:Button ID="Button2" runat="server" Text="《" /><br />
<asp:Button ID="Button1" runat="server" Text="<" /><br />
<asp:Button ID="Button3" runat="server" Text=">" /><br />
<asp:Button ID="Button4" runat="server" Text="》" />
</td>
<td align="left" width="50%">
<asp:ListBox ID="ListBox1" runat="server" Height="128px" Width="148px"></asp:ListBox>
</td>
</tr>
</table>
</div>
protected void Button1_Click(object sender, EventArgs e) { // < 移左
MoveSelectedItems(ListBox1, ListBox2);
}
protected void Button2_Click(object sender, EventArgs e) { // 《 全移左
MoveAllItems(ListBox1, ListBox2);
}
protected void Button3_Click(object sender, EventArgs e) { // > 移右
MoveSelectedItems(ListBox2, ListBox1);
}
protected void Button4_Click(object sender, EventArgs e) { // 》 全移右
MoveAllItems(ListBox2, ListBox1);
}
private void MoveSelectedItems(ListBox source, ListBox target) {
var items = source.Items.Cast<ListItem>().Where(i => i.Selected).ToList();
foreach (var item in items) {
source.Items.Remove(item);
target.Items.Add(item);
}
}
private void MoveAllItems(ListBox source, ListBox target) {
var items = source.Items.Cast<ListItem>().ToList();
foreach (var item in items) {
source.Items.Remove(item);
target.Items.Add(item);
}
}
ListBox.Items.Insert()。SelectionMode="Multiple" 可支援 Ctrl/Shift 多選。此範例簡潔易懂,可快速整合至任何需要項目雙向選擇的表單中。