[英]How to compare all the cells of DataGridView - C#
我是C#初學者。 您能幫忙比較一下DataGridView Column的所有單元格嗎,即如何檢查(Column)的所有單元格是否相等。 我想高效地做到這一點。
請讓我知道代碼,因為我不想在DataGridView中進行很多迭代。
我已經嘗試過以下一種方法:
bool *functionname()*
{
List<String> list_of_cellValues = new List<String>();
foreach (DataGridViewRow eachRow in BKCdataGrid.Rows)
{
String cellValue = eachRow.Cells[0].Value.ToString();
if (cellValue!= " " && cellValue!=null)
list_of_cellValues.Add(cellValue);
else
continue;
}
return (list_of_cellValues.Distinct().Count() == 1);
}
您可以使用此:
List<DataGridViewCell> l = new List<DataGridViewCell>();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int h = 0; h < dataGridView1.Rows[i].Cells.Count; h++)
{
l.Add(dataGridView1.Rows[i].Cells[h]);
}
}
bool result = (l.Distinct().Count() == 1);
檢查上一行在單元格中是否具有不同的值。 如果是這樣,則返回false。
bool functionname()
{
if (BKCdataGrid.RowCount == 0)
{
return false; // or true? Your call
}
// Get cell value in first row
object oldValue = BKCdataGrid.Rows[0].Cells[0].Value;
for (int i = 1; i < BKCdataGrid.RowCount; ++i)
{
if (BKCdataGrid.Rows[i].Cells[0].Value != oldValue)
{
return false; // they are some differences
}
}
// All cells are the same as the one in first row
return true;
}
您應該擴展此功能以接受列名作為參數,以提高可重用性。 重載接受列索引也將派上用場。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.