Method to move rows up and down in a DataTable

agent154 0 Tallied Votes 1K Views Share

I created this simple inherited class to add a function for moving a row up or down within a DataTable. Sometimes it is desired to do so, and I've seen a few people online looking for a way to do it.

Would be nicer if I knew how to properly overload the DataRow class as well, because I could then add a method to it to do it a bit cleaner, like row.MoveUp() .

using System;
using System.Data;

namespace SNS.Tools
{
    /// <summary>
    /// Choose whether to move the row Up or Down.
    /// </summary>
    public enum SNSDataTableMoveRow
    {
        Up,
        Down
    }
    
    /// <summary>
    /// An overloaded class to add functionality to the built-in
    /// System.Data.DataRow class.
    /// </summary>
    public class SNSDataTable : System.Data.DataTable
    {
        public SNSDataTable()
            : base()
        {
        }

        public SNSDataTable(string tableName)
            : base(tableName)
        {
        }

        public SNSDataTable(string tableName, string tableNamespace)
            : base(tableName, tableNamespace)
        {
        }

        public SNSDataTable(System.Runtime.Serialization.SerializationInfo info,
            System.Runtime.Serialization.StreamingContext context)
            : base(info, context)
        {
        }

        /// <summary>
        /// A custom method used to move a row up or down in a DataTable
        /// </summary>
        /// <param name="row">A DataRow which is a member of this DataTable.</param>
        /// <param name="direction">Up or Down.</param>
        /// <returns>The new row index after the move.</returns>
        public int MoveRow(DataRow row, SNSDataTableMoveRow direction)
        {
            if (row.Table != this)
                throw new ArgumentException("Row is not a member of this table.", "row");

            DataRow oldRow = row;
            DataRow newRow = this.NewRow();

            newRow.ItemArray = oldRow.ItemArray;

            int oldRowIndex = this.Rows.IndexOf(row);

            if (direction == SNSDataTableMoveRow.Down)
            {
                int newRowIndex = oldRowIndex + 1;

                if (oldRowIndex < (this.Rows.Count))
                {
                    this.Rows.Remove(oldRow);
                    this.Rows.InsertAt(newRow, newRowIndex);
                    return this.Rows.IndexOf(newRow);
                }
            }

            if (direction == SNSDataTableMoveRow.Up)
            {
                int newRowIndex = oldRowIndex - 1;

                if (oldRowIndex > 0)
                {
                    this.Rows.Remove(oldRow);
                    this.Rows.InsertAt(newRow, newRowIndex);
                    return this.Rows.IndexOf(newRow);
                }
            }

            return 0;
        }
    }
}