This would be my first time posting something of this sort. I apologize if it is not in the right (or most appropriate) area.
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.
using System.Data;
namespace SNS.Tools
{
public enum SNSDataTableMoveRow
{
Up,
Down
}
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)
{
}
public int MoveRow(DataRow row, SNSDataTableMoveRow direction)
{
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;
}
}
}