从数据网格读取时出错"Object Reference not set to an Instance of an object"



好的,所以我只是做了一个快速测试,看看我的代码是否设置为从 DataGrid 正确读取,它确实如此,但是一旦它完成读取,我就会"Object reference not set to an Instance of an object"错误,我不确定它指的是什么。是因为循环在rows到达 DataGrid 的末尾后继续吗?

public static void UploadFromExtrernalSource(PlantAreaCode_CreateView PACCreate)
{
// For each row in the DataGrid, and for each column, stores the information in a string.
for (int rows = 0; rows < PACCreate.dataGridView1.Rows.Count; rows++)
{
for (int col = 0; col < PACCreate.dataGridView1.Rows[rows].Cells.Count; col++)
{
string value = PACCreate.dataGridView1.Rows[rows].Cells[col].Value.ToString();
Console.WriteLine(value + ",");
}
}
}

编辑:同样当我打印到控制台时,它会在新行上打印每个值。为什么?

问题1:您正在尝试将其中一个单元格的null值转换为String

解决方案1:在将单元格值转换为String之前,请执行空检查。

问题2:您正在使用Console.WriteLine()方法来显示每个单元格,value.so 它以新Row/Line打印每个单元格值。

解决方案2:您需要使用Console.Write()方法而不是Console.WriteLine()来打印单元格值,并且在打印给定行中的所有单元格值后,您需要使用Console.WriteLine()打印新行。

建议:不需要每次在 for 循环中都声明字符串变量value,因此可以将字符串变量声明移出循环。

试试这个:

public static void UploadFromExtrernalSource(PlantAreaCode_CreateView PACCreate)
{
// For each row in the DataGrid, and for each column, stores the information in a string.
String value = String.Empty;
for (int rows = 0; rows < PACCreate.dataGridView1.Rows.Count; rows++)
{
for (int col = 0; col < PACCreate.dataGridView1.Rows[rows].Cells.Count; col++)
{
if(PACCreate.dataGridView1.Rows[rows].Cells[col].Value!=null)
{ 
value=PACCreate.dataGridView1.Rows[rows].Cells[col].Value;
Console.Write(value + ","); 
}
else 
{ value=String.Empty; }
}
Console.WriteLine();//it prints a new line 
}
}

嘿,我认为您正在尝试将单元格的 null 值转换为字符串。 尝试在将其转换为字符串之前检查 null 希望这会有所帮助!

相关内容

最新更新