I wrote the following code, but it does not work (It saves stupid things in my CSV file). What can be wrong? There are two columns in my 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);
}
This is the result I get in the saved file:
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 }
When you call this:
.Net is doing a “ToString” on each of those cells, not their values.
This is the type of
row.Cells[x]: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.aspxUsing the Value property will probably fix your problem: