不過,我有一個名字列[...]通過特定的列,而不是
所以我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();
}
}
}
您已經完成了這項工作嗎? – user7417866
我想按列而不是遍歷整個datagridview單元集合。我相信我在上面寫過。 – Arvayne
你是什麼意思「我想避免的另一個可選列」? –