2017-02-24 65 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

相關問題