首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET ListBox 雙向移動項目完整範例

     編輯:ASP.NET 基礎

在 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>

後端程式碼 (C#)

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 多選。
  • 實務上常搭配資料庫,移動後需同步更新排序欄位或關聯表。

此範例簡潔易懂,可快速整合至任何需要項目雙向選擇的表單中。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved