C# “错误”;对象引用未设置为对象的实例;从数据网格读取
好的,我只是做了一个快速测试,看看我的代码是否被设置为正确地从DataGrid读取,确实如此,但是一旦它完成读取,我就会得到错误“Object reference not set to a Instance of a Object”,我不确定它指的是什么。是因为C# “错误”;对象引用未设置为对象的实例;从数据网格读取,c#,datagrid,instance-variables,object-reference,C#,Datagrid,Instance Variables,Object Reference,好的,我只是做了一个快速测试,看看我的代码是否被设置为正确地从DataGrid读取,确实如此,但是一旦它完成读取,我就会得到错误“Object reference not set to a Instance of a Object”,我不确定它指的是什么。是因为行到达数据网格的末尾后循环继续吗 public static void UploadFromExtrernalSource(PlantAreaCode_CreateView PACCreate) { // For each row
行
到达数据网格的末尾后循环继续吗
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 + ",");
}
}
}
publicstaticvoid从外部资源上传(PlantAreaCode_CreateView PACCreate)
{
//对于DataGrid中的每一行和每一列,将信息存储在字符串中。
for(int rows=0;rows
编辑:当我打印到控制台时,它会在新行上打印每个值。为什么?嘿,我想你是想把单元格的空值转换成字符串。在将其转换为字符串之前,请尝试检查空值,希望这会有所帮助 问题1:您正在尝试将其中一个单元格中的
null
值转换为字符串
解决方案1:在将单元格值转换为字符串之前,请执行空检查
问题2:您正在使用控制台.WriteLine()
方法来显示每个单元格值。这样,它将在新的行/行中打印每个单元格值
解决方案2:您需要使用Console.Write()
方法而不是Console.WriteLine()
来打印单元格值,并且在打印给定行的所有单元格值后,您需要使用Console.WriteLine()
来打印新行
建议:您不需要每次在for循环中声明字符串变量值
,因此可以将字符串变量声明移出循环
试试这个:
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
}
}
publicstaticvoid从外部资源上传(PlantAreaCode_CreateView PACCreate)
{
//对于DataGrid中的每一行和每一列,将信息存储在字符串中。
字符串值=String.Empty;
for(int rows=0;rows
是否跟踪代码?检查实际的行数和单元格数对不起,我不确定你在问什么。未设置列和行的数量,因为这将在多个表上使用。Console.WriteLine始终在换行符中打印一个值。请尝试Console.WriteAnks为我找到该值,这确实澄清了我对此处实际发生的情况的理解:)