Sort DataTable

R

RP

I have a DataSet with one Table in it. It contains two columns: Date
and Amount. I want to sort the table on ascending order of Date after
the DataSet gets filled. How to sort the records of the DataTable?
 
J

Jon Skeet [C# MVP]

I have a DataSet with one Table in it. It contains two columns: Date
and Amount. I want to sort the table on ascending order of Date after
the DataSet gets filled. How to sort the records of the DataTable?

Do you have to sort the table, rather than using a DataView on the
DataTable and then sorting the view?

Jon
 
A

Andrew Cooper

Nirosh said:
what the hell you are trying to do here??

Sort a DataTable?

Nirosh

private DataTable SortDataTable(DataTable GetDataTable, string sort)
{
DataTable _NewDataTable = GetDataTable.Clone();
int rowCount = GetDataTable.Rows.Count;

DataRow[] foundRows = GetDataTable.Select(null, sort);
// Sort with Column name
for (int i = 0; i < rowCount; i++)
{
object[] arr = new object[GetDataTable.Columns.Count];
for (int j = 0; j < GetDataTable.Columns.Count; j++)
{
arr[j] = foundRows[j];
}
DataRow data_row = _NewDataTable.NewRow();
data_row.ItemArray = arr;
_NewDataTable.Rows.Add(data_row);
}

//Clear the incoming GetDataTable
GetDataTable.Rows.Clear();

for (int i = 0; i < _NewDataTable.Rows.Count; i++)
{
object[] arr = new object[GetDataTable.Columns.Count];
for (int j = 0; j < GetDataTable.Columns.Count; j++)
{
arr[j] = _NewDataTable.Rows[j];
}

DataRow data_row = GetDataTable.NewRow();
data_row.ItemArray = arr;
GetDataTable.Rows.Add(data_row);
}
return _NewDataTable;
}

 
B

BIMAL KOTHARI

Hello Just pass your data table and sort expression to sort (Date
and Amount) columns

Ok



Andrew Cooper said:
Nirosh said:
what the hell you are trying to do here??

Sort a DataTable?

Nirosh

private DataTable SortDataTable(DataTable GetDataTable, string sort)
{
DataTable _NewDataTable = GetDataTable.Clone();
int rowCount = GetDataTable.Rows.Count;

DataRow[] foundRows = GetDataTable.Select(null, sort);
// Sort with Column name
for (int i = 0; i < rowCount; i++)
{
object[] arr = new object[GetDataTable.Columns.Count];
for (int j = 0; j < GetDataTable.Columns.Count; j++)
{
arr[j] = foundRows[j];
}
DataRow data_row = _NewDataTable.NewRow();
data_row.ItemArray = arr;
_NewDataTable.Rows.Add(data_row);
}

//Clear the incoming GetDataTable
GetDataTable.Rows.Clear();

for (int i = 0; i < _NewDataTable.Rows.Count; i++)
{
object[] arr = new object[GetDataTable.Columns.Count];
for (int j = 0; j < GetDataTable.Columns.Count; j++)
{
arr[j] = _NewDataTable.Rows[j];
}

DataRow data_row = GetDataTable.NewRow();
data_row.ItemArray = arr;
GetDataTable.Rows.Add(data_row);
}
return _NewDataTable;
}


 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top