Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/260.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控件值时将for循环更改为foreach?_C#_For Loop_Datagridview_Foreach - Fatal编程技术网

C# 如何在遍历DataGridView控件值时将for循环更改为foreach?

C# 如何在遍历DataGridView控件值时将for循环更改为foreach?,c#,for-loop,datagridview,foreach,C#,For Loop,Datagridview,Foreach,我使用了以下代码: int count = DB.Rows.Count; for (int row = 0; row < count; row++) { int colCount = DB.Rows[row].Cells.Count; for (int col = 0; col < colCount; col++) { filewrite.Write(DB.Rows[row].Cells[col].Value + " "); }

我使用了以下代码:

int count = DB.Rows.Count;
for (int row = 0; row < count; row++)
{
    int colCount = DB.Rows[row].Cells.Count;

    for (int col = 0; col < colCount; col++)
    {
        filewrite.Write(DB.Rows[row].Cells[col].Value + " ");
    }

    filewrite.WriteLine("");
}
有人能帮我或给我一个提示吗

编辑

差不多了!,现在我需要此循环不读取自动生成为空行的最后一行:

foreach (DataGridViewRow item in this.DB.Rows)
{
    foreach (DataGridViewCell item2 in item.Cells)
    {   
        if(item2.Value != null)
        filewrite.Write(item2.Value.ToString() + " ");
    }

    filewrite.WriteLine("");
}
如何省略最后一个空行?

请尝试以下代码:

foreach (DataGridViewRow row in this.DB.Rows)
{
    // Add this to break the loop when row is last blank row
    if (row.IsNewRow)
        break;

    foreach (DataGridViewCell cell in row.Cells)
    {
        if (cell.Value != null)
            filewrite.Write(cell.Value.ToString() + " ");
    }
    file.WriteLine();
}

我假设您正在尝试将每行单元格中的所有值打印到文本文件中。如果是这样的话,这应该完成任务。

您的第一个foreach不应该是
DataGridViewRow
类型,第二个
DataGridViewColumn
类型吗?
foreach (DataGridViewRow row in this.DB.Rows)
{
    // Add this to break the loop when row is last blank row
    if (row.IsNewRow)
        break;

    foreach (DataGridViewCell cell in row.Cells)
    {
        if (cell.Value != null)
            filewrite.Write(cell.Value.ToString() + " ");
    }
    file.WriteLine();
}