我编写了以下代码,但它不起作用(它在我的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}
答案 0 :(得分:4)
当你这样称呼时:
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);