我编写了以下代码,但是不起作用(它将愚蠢的内容保存在CSV文件中)。有什么事吗我的DataGridView中有两列。

var strValue = new StringBuilder();

foreach(DataGridViewRow row in dataGridView1.Rows)
{
    strValue.AppendLine(row.Cells[0] + "," + row.Cells[1]);
}

string strFile = Properties.Settings.Default.AutoCompleteFile; //File Path

if (!string.IsNullOrEmpty(strValue.ToString()))
{
    File.WriteAllText(strFile, strValue.ToString(), Encoding.UTF8);
}


这是我在保存的文件中得到的结果:


  DataGridViewTextBoxCell {ColumnIndex = 0,RowIndex = 0},DataGridViewTextBoxCell {ColumnIndex = 1,RowIndex = 0}
  DataGridViewTextBoxCell {ColumnIndex = 0,RowIndex = 1},DataGridViewTextBoxCell {ColumnIndex = 1,RowIndex = 1}
  DataGridViewTextBoxCell {ColumnIndex = 0,RowIndex = 2},DataGridViewTextBoxCell {ColumnIndex = 1,RowIndex = 2}
  DataGridViewTextBoxCell {ColumnIndex = 0,RowIndex = 3},DataGridViewTextBoxCell {ColumnIndex = 1,RowIndex = 3}
  DataGridViewTextBoxCell {ColumnIndex = 0,RowIndex = 4},DataGridViewTextBoxCell {ColumnIndex = 1,RowIndex = 4}
  DataGridViewTextBoxCell {ColumnIndex = 0,RowIndex = 5},DataGridViewTextBoxCell {ColumnIndex = 1,RowIndex = 5}
  DataGridViewTextBoxCell {ColumnIndex = 0,RowIndex = 6},DataGridViewTextBoxCell {ColumnIndex = 1,RowIndex = 6}
  DataGridViewTextBoxCell {ColumnIndex = 0,RowIndex = 7},DataGridViewTextBoxCell {ColumnIndex = 1,RowIndex = 7}
  DataGridViewTextBoxCell {ColumnIndex = 0,RowIndex = 8},DataGridViewTextBoxCell {ColumnIndex = 1,RowIndex = 8}
  DataGridViewTextBoxCell {ColumnIndex = 0,RowIndex = 9},DataGridViewTextBoxCell {ColumnIndex = 1,RowIndex = 9}
  DataGridViewTextBoxCell {ColumnIndex = 0,RowIndex = 10},DataGridViewTextBoxCell {ColumnIndex = 1,RowIndex = 10}

最佳答案

当您致电:

strValue.AppendLine(row.Cells[0] + "," + row.Cells[1]);


.Net在每个这些单元格上执行“ ToString”,而不是它们的值。
这是row.Cells[x]的类型:http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.aspx

使用Value属性可能会解决您的问题:

strValue.AppendLine(row.Cells[0].Value + "," + row.Cells[1].Value);

关于c# - 将DataGridView导出到CSV文本文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8646753/

10-12 15:14