views:

119

answers:

1

I have datatable and I am displaying those values in the datagridview with the helping of code :

   dataGridView1.ColumnCount = TableWithOnlyFixedColumns.Columns.Count;
   dataGridView1.RowCount = TableWithOnlyFixedColumns.Rows.Count;
   for (int i = 0; i < dataGridView1.RowCount; i++)
   {
       for (int j = 0; j < dataGridView1.ColumnCount; j++)
       {
           dataGridView1[j, i].Value = TableWithOnlyFixedColumns.Rows[i][j].ToString();
       }
   }
   TableExtractedFromFile.Clear();
   TableWithOnlyFixedColumns.Clear();

Now I want to save the records in the datatable in csv file.How can I do that ?

+1  A: 

You could do this:

// we'll use these to check for rows with nulls
var columns = yourTable.Columns
    .Cast<DataColumn>();

// say the column you want to sort by is called "Date"
var rows = yourTable.Select("", "Date ASC"); // or "Date DESC"

using (var writer = new StreamWriter(yourPath)) {
    for (int i = 0; i < rows.Length; i++) {
        DataRow row = 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));
    }
}
Dan Tao
@Dan Tao,If there is null value or nothing at all(empty string) then that whole row should not be stored in csv file.How can I do that ?
Harikrishna
@Harikrishna: I've updated the code with a suggestion on how you might do this.
Dan Tao
@Dan Tao,Thank You..+1 For The Great Answer...
Harikrishna
@Dan Tao, If there is one column in the datatable type of datetime then I want this records in the csv file sorted by date?
Harikrishna
@Harikrishna: You can retrieve your rows sorted using the `DataTable.Select` method. I've updated my answer with an example.
Dan Tao
@Dan Tao,What is the best way to sort the records Datatable.Select orDatatable.DefaultView.Sort ?
Harikrishna
@Dan Tao,Thank You Very Much For Your Help.Your code is very helpful to me.
Harikrishna
@Dan Tao,If there is datagridview instead of datatable then how should I do that ?
Harikrishna