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();
}