在 ASP.NET Web Forms 開發中,DataList 是一個常用的資料顯示控制項。雖然它不像 GridView 內建排序、分頁功能,但透過自訂命令事件,我們可以輕鬆實現資料列的上移、下移操作。本文將完整示範如何在 DataList 綁定資料後,加入「上移」、「下移」按鈕,並在後端處理排序邏輯。
在 DataList 的 ItemTemplate 中放置兩個 LinkButton 或 Button,分別設定 CommandName 為 "Up" 和 "Down",並將 CommandArgument 綁定為當前行的索引或主鍵值。
<asp:DataList ID="dlItems" runat="server" OnItemCommand="dlItems_ItemCommand">
<ItemTemplate>
<%# Eval("Title") %>
<asp:LinkButton ID="btnUp" runat="server" CommandName="Up" CommandArgument='<%# Container.ItemIndex %>'>上移</asp:LinkButton>
<asp:LinkButton ID="btnDown" runat="server" CommandName="Down" CommandArgument='<%# Container.ItemIndex %>'>下移</asp:LinkButton>
</ItemTemplate>
</asp:DataList>
在 Code-behind 中處理 ItemCommand 事件,根據 CommandName 判斷是上移還是下移,取得當前索引與相鄰索引的主鍵,呼叫資料存取層交換顯示順序欄位,最後重新綁定資料。
protected void dlItems_ItemCommand(object source, DataListCommandEventArgs e)
{
int index = e.Item.ItemIndex;
string currentId = DataList1.DataKeys[index].ToString();
if (e.CommandName == "Up")
{
if (index > 0)
{
string prevId = DataList1.DataKeys[index - 1].ToString();
// 呼叫資料層交換排序欄位
BizLayer.SwapDisplayOrder(currentId, prevId);
BindDataList();
}
else
{
ShowMessage("已經是第一筆,無法上移。");
}
}
else if (e.CommandName == "Down")
{
if (index < DataList1.Items.Count - 1)
{
string nextId = DataList1.DataKeys[index + 1].ToString();
BizLayer.SwapDisplayOrder(currentId, nextId);
BindDataList();
}
else
{
ShowMessage("已經是最後一筆,無法下移。");
}
}
}
在資料存取類別中撰寫交換兩筆記錄顯示順序的方法,通常是更新一個 SortOrder 或 DisplayNum 欄位。
public static void SwapDisplayOrder(string id1, string id2)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
string sql = @"UPDATE Titles SET DisplayNum = CASE TitleID
WHEN @id1 THEN (SELECT DisplayNum FROM Titles WHERE TitleID = @id2)
WHEN @id2 THEN (SELECT DisplayNum FROM Titles WHERE TitleID = @id1)
END
WHERE TitleID IN (@id1, @id2)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@id1", id1);
cmd.Parameters.AddWithValue("@id2", id2);
conn.Open();
cmd.ExecuteNonQuery();
}
}
你可以從 GitHub 範例專案 下載完整可執行的 Visual Studio 解決方案,包含資料庫腳本、前後端完整代碼,方便直接參考或移植到專案中。
總結:透過 DataList 的 ItemCommand 事件搭配資料層的排序欄位交換,即可輕鬆實現資料列的上移下移功能。關鍵在於正確取得當前與相鄰行的主鍵,並在資料庫層面完成順序互換,最後重新綁定呈現即可。