Pages

Friday, March 4, 2011

Reorder the datatable

public void DoReorder(int oldIndex, int newIndex, ref DataTable DataSource, string SortOrderField)
        {
            if (DataSource is DataTable)
            {
                DataRowCollection rows = ((DataTable)DataSource).Rows;
                int NewListOrder = Convert.ToInt32(rows[newIndex][SortOrderField]);

                if (oldIndex < newIndex) //item moved down
                {
                    for (int i = oldIndex + 1; i <= newIndex; i++)
                    {
                        rows[i][SortOrderField] =
                    Convert.ToInt32(rows[i][SortOrderField]) - 1;
                    }
                }
                else  //item moved up
                {
                    for (int i = oldIndex - 1; i >= newIndex; i--)
                    {
                        rows[i][SortOrderField] =
                    Convert.ToInt32(rows[i][SortOrderField]) + 1;
                    }
                }
                rows[oldIndex][SortOrderField] = NewListOrder;

            }
            else
            {
                throw new InvalidOperationException
            ("DataSource is not a System.Data.DataTable.");
            }
        }

No comments:

Post a Comment