I have a Gridview with different items, ordered by the integer column "Order". I am saving the DataTable that feeds the Gridview as "Session Parameter".
Item Order LinkButtons
----------------------------------
Item1 1 up down
Item2 2 up down
Item3 3 up down
The idea is to customize the order of the items by moving them up and down with the LinkButtons.
This is what I do:
-
I get the row index from the RowClick Event
LinkButton lb = (sender as LinkButton); string OrderNr = lb.CommandArgument; int OrderNummer = Convert.ToInt16(OrderNr); GridViewRow row = (GridViewRow)lb.NamingContainer; int idx = row.RowIndex;
-
Call the Session table and change the Order Parameter
DataTable t = Session["SessionData"] as DataTable; t.Rows[idx][1] = Convert.ToString(OrderNummer - 1); t.Rows[idx-1][1] = Convert.ToString(OrderNummer);
-
I then reorder the DataTable and bind it back to the Grid
t.DefaultView.Sort = "OderNr"; t = t.DefaultView.ToTable();
This unfortunately works only on the first Operation. Afterwards what is returned from t.Rows[idx] is unpredictable to me as the Gridrow Row Index doesn’t match the DataTable Row index.
Very confusing
2
Answers
Not influent in C#, code may need optimization/fine-tuning.
aspx
Page_Load
Get_DataTable
Btn_UP_Command
Btn_DN_Command
The problem here is that you using "default" view for the grid binding.
But default view DOES NOT change the row index of the base table!!!
This results in 2 possible solutions:
You consider using dataitem index from the GridView, and NOT row index.
Or, simpler is to sort the base table.
You can do this with this:
Note VERY close in above, we have to shove the rstData table BACK into session[], since we have re-built the table with .ToTable(), and that in effect is a new instance of the object.
So, here is a working example (I have included the MyOrder column in this example). Also keep in mind, that rows are 0 based, and your example started with 1. For this example, "MyOrder" column starts at 0, and not one.
So, say this markup:
And code behind:
The result is this: