在这种情况下,我个人会使用中继器并将其绑定到您的 LinqDataSource。
然后,您可以处理 OnItemDataBound 事件并获取e.Item.DataItem
每一行的对象。获取对向上和向下按钮的引用,并将按钮e.Item.FindControl("btnUP") as Button
的命令参数设置为 DataItem 的序列号。
然后在按钮的 OnClick 事件中,使用 CommandArgument 重新排序和更新您的 LinqDataSource - 然后重新绑定中继器以显示更改。
编辑 - 增加清晰度
假设您有 aList<Employee>
作为数据源,并且 Employee 对象定义为
public class Employee
{
int EmployeeID;
int PlaceInLine; // value indicating the sequence position
string Name;
}
您的向上和向下按钮可以在您的 ListView 中定义,如下所示:
<asp:Button ID="btnUpButton" runat="server"
CommandArgument='<%#Eval("EmployeeID") %>' OnClick="btnUp_Click" />
单击按钮时,您可以处理该事件 - 这假设您将员工列表作为私有变量访问:
private List<Employee> _Employees;
protected void btnUp_Click(object sender, EventArgs e)
{
Button btnUp = sender as Button;
int employeeID = int.Parse(btnUp.CommandArgument); // get the bound PK
Employee toMoveUp = _Employees.Where(e=>e.EmployeeID == employeeID).FirstOrDefault();
// assuming PlaceInLine is unique among all employees...
Employee toMoveDown = _Employees.Where(e=>e.PlaceInLine == toMoveUp.PlaceInLine + 1).FirstOrDefault();
// at this point you need to ++ the employees sequence and
// -- the employee ahead of him (e.g. move 5 to 6 and 6 to 5)
toMoveUp.PlaceInLine ++;
toMoveDown.PlaceInLine --;
// save the list
DataAccessLayer.Save(_Employees);
//rebind the listivew
myListView.DataBind();
}