【发布时间】:2018-11-28 01:26:55
【问题描述】:
我的代码是将数据网格保存到 csv。当处理到
value = dr.Cells[i].Value.ToString();
错误信息如下:System.Windows.Forms.DataGridViewCell.Value.get return null。
然后,我添加极端情况以检查单元格是否为空,并将这些单元格替换为“空”。
foreach (DataGridViewRow rw in this.dataGridView1.Rows)
{
for (int i = 0; i < rw.Cells.Count; i++)
{
if (rw.Cells[i].Value == System.DBNull.Value)
{
swOut.Write("Null");
}
}
}
但错误信息仍然存在。
以下是我的代码:
public void writeCSV(DataGridView gridIn, string outputFile)
{
//test to see if the DataGridView has any rows
if (gridIn.RowCount > 0)
{
string value = "";
DataGridViewRow dr = new DataGridViewRow();
StreamWriter swOut = new StreamWriter(outputFile);
foreach (DataGridViewRow rw in this.dataGridView1.Rows)
{
for (int i = 0; i < rw.Cells.Count; i++)
{
if (rw.Cells[i].Value == System.DBNull.Value)
{
swOut.Write("Null");
}
}
}
//write header rows to csv
for (int i = 0; i <= gridIn.Columns.Count - 1; i++)
{
if (i > 0)
{
swOut.Write(",");
}
swOut.Write(gridIn.Columns[i].HeaderText);
}
swOut.WriteLine();
//write DataGridView rows to csv
for (int j = 0; j <= gridIn.Rows.Count - 1; j++)
{
if (j > 0)
{
swOut.WriteLine();
}
dr = gridIn.Rows[j];
for (int i = 0; i <= gridIn.Columns.Count - 1; i++)
{
if (i > 0)
{
swOut.Write(",");
}
value = dr.Cells[i].Value.ToString();
//replace comma's with spaces
value = value.Replace(',', ' ');
//replace embedded newlines with spaces
value = value.Replace(Environment.NewLine, " ");
swOut.Write(value);
}
}
swOut.Close();
}
}
【问题讨论】:
-
试试:
if (rw.Cells[i].Value == null)
标签: c# csv datagridview datagrid null