2010-05-01 30 views
1

存储在CSV文件中的记录我有数据表,我在DataGridView与代码的帮扶显示这些值:从数据表

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(); 

现在我想保存在CSV文件中的数据表中的记录。我怎样才能做到这一点 ?

回答

1

你可以这样做:

// 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)); 
    } 
} 
+0

@丹道,如果在所有的(空字符串)空值或没有那么整行不应该被保存在CSV file.How我能做到这一点? – Harikrishna 2010-05-01 07:12:05

+0

@Harikrishna:我已经更新了代码,并提供了关于如何执行此操作的建议。 – 2010-05-01 20:04:48

+0

@Dan Tao,Thank You .. + 1 For The Answer ... – Harikrishna 2010-05-03 04:41:23