So, I have a ListView that contains a steps in a process. On the left there is a Label simply stating which step it is, and on the right is a TextBox with the instructions. Then to the right of that TextBox is the usual edit and delete buttons, but I also have an up-arrow and a down-arrow. If clicked, I would like the current set of items to be moved into that slot.
This ListView is bound by a LinqDataSource and if I could just access the property of an item from that set where the button was clicked, I could just call ListView.DataBind() and it would sort itself.
The property I'm talking about is what is in the Label saying which step it is. I have it set up like this:
<asp:Label ID="lblStepNumber" runat="server" Text='<%# Eval( "StepNumber", "Step #{0}" ) %>' />
So if I can just do something like
ListView.Items.[Where_btn_clicked].StepNumber++;
ListView.Items.[Where_btn_clicked+1].StepNumber--;
ListView.DataBind();
That would be easiest, but I don't know how to access this property.
I personally would use a Repeater in this case and bind it to your LinqDataSource.
You may then handle the OnItemDataBound event and grab the e.Item.DataItem
object for each row. Get a reference to your Up and Down buttons using e.Item.FindControl("btnUP") as Button
and set the command argument of the button to your DataItem's sequence number.
Then in the button's OnClick event, use the CommandArgument to reorder and update your LinqDataSource - then rebind the repeater to display the changes.
Edit - adding further clarity
Let's say you have a List<Employee>
as your data source, and the Employee object is defined as
public class Employee
{
int EmployeeID;
int PlaceInLine; // value indicating the sequence position
string Name;
}
Your Up and Down buttons could be defined in your ListView like this:
<asp:Button ID="btnUpButton" runat="server"
CommandArgument='<%#Eval("EmployeeID") %>' OnClick="btnUp_Click" />
When the button is clicked, you can handle the event - this assumes you have your list of employees accessible as a private variable:
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();
}