Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法在datagridview中循环单元格_C#_Datagridview - Fatal编程技术网

C# 无法在datagridview中循环单元格

C# 无法在datagridview中循环单元格,c#,datagridview,C#,Datagridview,我有一个datagrid,它返回4列244行。第4列有3种不同的状态“已完成”、“正在进行”、“未完成”,在所有单元格中。我需要遍历第4列中的每个单元格,读取值,将它们相加并存储在变量包中。因此,我需要有3个变量来表示3种状态。我该怎么做 Here is the code that I have. I am not sure if this is the right way to do it or if there is 更简单的方法是,在我运行它之后,它一直告诉我“对象引用未设置为对象的实例

我有一个datagrid,它返回4列244行。第4列有3种不同的状态“已完成”、“正在进行”、“未完成”,在所有单元格中。我需要遍历第4列中的每个单元格,读取值,将它们相加并存储在变量包中。因此,我需要有3个变量来表示3种状态。我该怎么做

Here is the code that I have. I am not sure if this is the right way to do it or if there is
更简单的方法是,在我运行它之后,它一直告诉我“对象引用未设置为对象的实例”

listNames=newlist();
foreach(dataGridView1.Rows中的DataGridViewRow行)
{
foreach(row.Cells中的DataGridViewCell单元格)
{
int i=0;
if(cell.Value.ToString()=“已完成”)
{
i++;
i+=i;
}  
Show(i.ToString());
}
}
}

查看并使用调试器对代码进行测试,了解这个简单示例的情况

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    foreach (DataGridViewCell cell in row.Cells)
    {
        Console.WriteLine(Convert.ToString(cell.Value));
    }
}

看起来像单元格。值可以为null,因此替换

if  (cell.Value.Equals("Completed"))


无论如何,String==运算符被重载以按值进行比较,因此此代码将运行OK

如果要对它们进行计数,请尝试以下操作

var iRows = dataGridView1.Rows.Cast<DataGridViewRow>();
var statusLookup = iRows.ToLookup(r => r.Cells[3].Value + ""); 
int countOfCompleted = statusLookup["Completed"].Count();
var iRows=dataGridView1.Rows.Cast();
var statusLookup=iRows.ToLookup(r=>r.Cells[3].Value+“”);
int countOfCompleted=statusLookup[“Completed”].Count();

如果有数据源,最好使用该单元格,因为它显然没有任何价值。如果您只关心ColumnIndex 3,为什么还要循环遍历单元格呢?您还声明了一个
int i
,但从不递增它。。我将发布一些东西,以便您可以轻松地使用它来遵循一个可能您会通过使用调试器单步执行代码来了解发生了什么。如果DGV是
allowUserToAddress
==true,您正在循环执行@MethodMan中解释的多了一行。谢谢,我将等待它。刚刚完成了它。它将一行一行地遍历每个单元格。现在,以这个示例为例,更改内部foreach以适应您要执行的操作。。另外,请看我关于在何处初始化计数器的评论,在您的情况下,
i
应该位于内部foreach循环的外部。好的,让我试试。几分钟后会让你知道它是否有效。谢天谢地,我使用了一个if语句来循环遍历单元格,但是我无法得到每个状态的总结果。下面是循环if(cell.Value.ToString()=“Completed”){i++;i+=i;}
if  (cell.Value == "Completed")
var iRows = dataGridView1.Rows.Cast<DataGridViewRow>();
var statusLookup = iRows.ToLookup(r => r.Cells[3].Value + ""); 
int countOfCompleted = statusLookup["Completed"].Count();