C# 将DataGridView转换为Windows窗体C上的文本文件#

C# 将DataGridView转换为Windows窗体C上的文本文件#,c#,winforms,datagridview,streamwriter,C#,Winforms,Datagridview,Streamwriter,我有一个要写入文本文件的datagridview。这是我的密码: private void WriteToFile_Click(object sender, EventArgs e) { StreamWriter sW = new StreamWriter("list.txt"); for (int i = 0; i < 6; i++) { string lines = ""; for (int col = 0; col < 6

我有一个要写入文本文件的datagridview。这是我的密码:

private void WriteToFile_Click(object sender, EventArgs e)
{
    StreamWriter sW = new StreamWriter("list.txt");
    for (int i = 0; i < 6; i++)
    {
        string lines = "";
        for (int col = 0; col < 6; col++)
        {
            lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + 
                dataGridView.Rows[i].Cells[col].Value.ToString();
        }
        sW.WriteLine(lines);
        sW.Close();
    }
}
private void WriteToFile\u单击(对象发送方,事件参数e)
{
StreamWriter sW=新StreamWriter(“list.txt”);
对于(int i=0;i<6;i++)
{
字符串行=”;
for(int col=0;col<6;col++)
{
行+=(string.IsNullOrEmpty(行)?“”:“,”+
dataGridView.Rows[i].Cells[col].Value.ToString();
}
sW.WriteLine(行);
sW.Close();
}
}
当我点击按钮时,会出现一个错误:

System.NullReferenceException

尝试在循环中使用for each:

StreamWriter sW = new StreamWriter("list.txt");
foreach (DataGridViewRow r in dataGridView.Rows) {
    string lines = "";
    foreach (DataGridViewCell c in r.Cells) {
        lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + dataGridView.Rows[i].Cells[col].Value == null ? string.Empty : dataGridView.Rows[i].Cells[col].Value;
    }

    sW.WriteLine(lines);
}

网格中的一个或多个值是
null
,或者换句话说,“nothing”。所以,当您使用访问
dataGridView.Rows[i].Cells[col].Value属性,然后将其转换为字符串时,您试图将z
null
转换为字符串,然后引发异常。 您应该检查空值,如下所示:

(如果您使用的是.net 4.6)

注意
Value

(如果您使用的是较旧的.net)

希望这有帮助

编辑: 由于您得到的是
System.ArgumentOutOfRangeException
,请确保您没有超出网格的界限-尝试访问多个行或列。为确保您处于约束状态,请使用

for (int i = 0; i < dataGridView.RowCount; i++)
for(int i=0;i
对于您的第一个循环和

for (int col = 0; col < dataGridView.ColumnCount; col++)
for(int col=0;col

第二,嗨,乔,试着在你的问题上再努力一点。例如,当您通过WriteToFile\u单击进行调试时,它在哪里返回空引用?类似于此的详细信息帮助我们,帮助您。检查您的网格是否小于6x6Oh对不起,它在第+=(string.IsNullOrEmpty(lines)?“”:“,”)+dataGridView.Rows[i].Cells[col].Value.ToString()行上返回空引用;如何检查@wdcYour cell没有值,因此尝试对其调用ToString()将无效。始终保存到完整路径,顺便说一句。看起来确实更好,但在执行ToString()之前,您确实需要检查c.Value是否为null,否则您将获得NullReferenceException。我在尝试代码时发现,发生了类型为“System.ArgumentOutOfRangeException”的未经处理的异常
for (int i = 0; i < dataGridView.RowCount; i++)
for (int col = 0; col < dataGridView.ColumnCount; col++)