2017-02-24 133 views
-1

在这个例子中,我正在循环遍历每个单元格。
但是,我有一个名称列和另一个我想避免的可选列。所以我宁愿要循环访问一组特定的列,而不使用可选的列,但我不知道如何。如何将DataGridView中的特定列设置为0(如果它为空)?

这是我怎么没彻底清扫:

foreach (DataGridViewRow row in DGVExcel.Rows) 
{ 
    for (int i = 0; i < row.Cells.Count; i++) 
    { 
     if (row.Cells[i].Value == null || row.Cells[i].Value == DBNull.Value || 
      String.IsNullOrWhiteSpace(row.Cells[i].Value.ToString())) 
     { 
      row.Cells[i].Value = 0; 
      //DGVExcel.RefreshEdit(); 
     } 
    } 
} 
+1

您已经完成了这项工作吗? – user7417866

+0

我想按列而不是遍历整个datagridview单元集合。我相信我在上面写过。 – Arvayne

+1

你是什么意思“我想避免的另一个可选列”? –

回答

2

不过,我有一个名字列[...]通过特定的列,而不是

所以我rather'd环

如果我理解正确的话,你可以得到列的索引,您可以跳过一个for循环:

int colindex = DGVExcel.Columns["SpecificColumnName"].Index; 

foreach (var row in DGVExcel.Rows) 
{ 
    if (row.Cells[colindex].Value == null || row.Cells[colindex].Value == DBNull.Value || 
      String.IsNullOrWhiteSpace(row.Cells[colindex].Value.ToString())) 
    { 
     row.Cells[colindex].Value = 0; 
     //DGVExcel.RefreshEdit(); 
    } 

} 

编辑

有没有办法列出排除的列,而不是包含的,因为上市的每个人都成为凌乱

在这种情况下,我会用2把它的for循环。基本上,您可以将所有名称保存在列表中,并检查它是否包含当前列的名称,如果没有,则可以替换0

List<string> ExcludedColumnsList = new List<string> { "ExcludedColumnName_1", "ExcludedColumnName_2" };   

foreach (DataGridViewRow row in DGVExcel.Rows) 
{ 
    for (int i = 0; i < row.Cells.Count; i++) 
    { 
     if (!ExcludedColumnsList.Contains(DGVExcel.Columns[i].Name)) 
     { 
      if (row.Cells[i].Value == null || row.Cells[i].Value == DBNull.Value || 
        String.IsNullOrWhiteSpace(row.Cells[i].Value.ToString())) 
      { 
       row.Cells[i].Value = 0; 
       //DGVExcel.RefreshEdit(); 
      } 
     } 
    } 
} 

另一种选择也可以使用linq。获取除排除列以外的所有索引,仅通过这些索引进行分析:

List<string> ExcludedColumnsList = new List<string> { "ExcludedColumnName_1", "ExcludedColumnName_2" }; 
List<int> indexList = dataGridView1.Columns.Cast<DataGridViewColumn>() 
      .Where(x => !ExcludedColumnsList.Contains(x.Name)) 
      .Select(x => x.Index).ToList(); 

foreach (DataGridViewRow row in DGVExcel.Rows) 
{ 
    foreach (int i in indexList) 
    { 
     if (row.Cells[i].Value == null || row.Cells[i].Value == DBNull.Value || 
       String.IsNullOrWhiteSpace(row.Cells[i].Value.ToString())) 
     { 
      row.Cells[i].Value = 0; 
      //DGVExcel.RefreshEdit(); 
     } 
    } 
} 
+0

嗯,现在我想到了这一点,似乎我将有20列循环,只有2列排除在外。有没有办法列出被排除的列而不是包含的列,因为列出每个列将是混乱的。 – Arvayne

+1

@Arvayne是的。你剩下你的2个for循环,你可以选择是否要使用linq或额外的if子句,看看我的编辑 –

+0

该列表完美工作!除此之外,我还了解如何正确使用列表。 – Arvayne

相关问题