Question

I sort the records of the datatable datewise with the column TradingDate which is type of datetime.

TableWithOnlyFixedColumns.DefaultView.Sort = "TradingDate asc";

Now I want to store these sorted records into csv file but stored records are not sorted by date.

 TableWithOnlyFixedColumns.DefaultView.Sort = "TradingDate asc";
  DataTable newTable = TableWithOnlyFixedColumns.Clone();
  newTable.DefaultView.Sort = TableWithOnlyFixedColumns.DefaultView.Sort;
  foreach (DataRow oldRow in TableWithOnlyFixedColumns.Rows)
  {
     newTable.ImportRow(oldRow);
  }
  // we'll use these to check for rows with nulls
  var columns = newTable.DefaultView.Table.Columns.Cast<DataColumn>();
  using (var writer = new StreamWriter(@"C:\Documents and Settings\Administrator\Desktop\New.csv"))
  {
     for (int i = 0; i < newTable.DefaultView.Table.Rows.Count; i++)
     {
        DataRow row = newTable.DefaultView.Table.Rows[i];
        // check for any null cells
        if (columns.Any(column => row.IsNull(column)))
        continue;
       string[] textCells = row.ItemArray
      .Select(cell => cell.ToString()) // may need to pick a text qualifier here
      .ToArray();
      // check for non-null but EMPTY cells
      if (textCells.Any(text => string.IsNullOrEmpty(text)))
      continue;
      writer.WriteLine(string.Join(",", textCells));
    }
 }

So how to store sorted records in csv file ?

Was it helpful?

Solution

This line of code;

DataRow row = newTable.DefaultView.Table.Rows[i]; 

is referencing the unsorted DataTable behind the DataView. You need to use a DataRowView instead of a DataRow and access the sorted rows from the DataView;

DataRowView row = newTable.DefaultView[i]; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top