C# 将数据网格视图单元格转换为单个字符串

C# converting datagrid view cells in to a single string

我使用以下方法将数据网格视图中的单元格转换为单个字符串,并在单击按钮时在控制台中打印该字符串!

private void button3_Click(object sender, EventArgs e)
        {
            String file = "";
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    file = file + dataGridView1.Rows[i].Cells[j].Value.ToString();
                }
            }
            Console.WriteLine(file);
        }

但是我收到以下错误消息“发生了 'System.NullReferenceException' 类型的未处理异常”,代码行 dataGridView1.Rows[i].Cells[j].Value.ToString();突出显示!我该如何解决这个问题?

您必须像这样检查单元格中是否存在值 ->

if (dataGridView1.Rows[i].Cells[j].Value!=null)
{    
file = file + dataGridView1.Rows[i].Cells[j].Value.ToString();
}
  private void button3_Click(object sender, EventArgs e)
            {
                string file = "";
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    for (int j = 0; j < dataGridView1.Rows[i].Cells.Count; j++)
                    {
                       if(dataGridView1.Rows[i].Cells[j].Value!=null)
                         {
                      file+=dataGridView1.Rows[i].Cells[j].Value.ToString();
                         }
                       else
                         {
                           file+="";
                         }
                    }
                }
                Console.WriteLine(file);
            }

我认为 j 的循环是错误的。让我们试试这个。