Introduction
Once I came across a situation where the client wanted to swap the rows in a GridView
. I will show a sample example of doing the same.
Straight to the Program
The datasource is basically a datatable with two columns viz. Name
, Address
:
DataTable dtsource = new DataTable();
dtsource.Columns.Add("Name");
dtsource.Columns.Add("Address");
dtsource.Rows.Add("Name1", "Address1");
dtsource.Rows.Add("Name2", "Address2");
dtsource.Rows.Add("Name3", "Address3");
dtsource.Rows.Add("Name4", "Address4");
dtsource.Rows.Add("Name5", "Address5");
dtsource.Rows.Add("Name6", "Address6");
dtsource.Rows.Add("Name7", "Address7");
dtsource.Rows.Add("Name8", "Address8");
dtsource.Rows.Add("Name9", "Address9");
dtsource.Rows.Add("Name10", "Address10");
I consume the same for the GridView
at the page load event.
I wrote the swapping logic in the Row Command event since it is the event that gets fired when a control (e.g. Button
) is clicked that resides inside the GridView
.
Obviously, the Button’s CommandName as well as the Command Argument need to be set.
In this case, the CommandName is set to Up & Down respectively while I pass the grid’s row id in the Command Argument.
CommandName="Up" CommandArgument=<%# Container.DataItemIndex %>
The Swap
method whose signature is Swap(int rowid, string option)
does the row swapping:
private void Swap(int rowid, string option)
{
if (option == "UP")
{
for (int i = 0; i <= 1; i++)
{
string temp = grdRowMovementDemo.Rows[rowid - 1].Cells[i].Text;
grdRowMovementDemo.Rows[rowid - 1].Cells[i].Text =
grdRowMovementDemo.Rows[rowid].Cells[i].Text;
grdRowMovementDemo.Rows[rowid].Cells[i].Text = temp;
}
}
else
{
for (int i = 0; i <= 1; i++)
{
string temp = grdRowMovementDemo.Rows[rowid].Cells[i].Text;
grdRowMovementDemo.Rows[rowid].Cells[i].Text =
grdRowMovementDemo.Rows[rowid + 1].Cells[i].Text;
grdRowMovementDemo.Rows[rowid + 1].Cells[i].Text = temp;
}
}
}
I wrote the calling function in the RowCommand
event of the GridView
. It is as under:
int rowid = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Up")
{
if (rowid > 0)
Swap(rowid, "UP");
}
if (e.CommandName == "Down")
{
if (rowid != grdRowMovementDemo.Rows.Count - 1)
Swap(rowid, "DOWN");
}
Conclusion
I have shown one of the ways by which we can achieve the row movement in the GridView
. Any better suggestion/solution is always welcome.
History
- 24th May, 2009: Initial post