我是C#初学者。你可以帮助如何比较DataGridView列的所有单元格,即如何检查(列的)所有单元格是否具有相同的值。 我想高效地执行此操作。
Pl让我知道代码,因为我不想做很多循环遍历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);
}
答案 0 :(得分:0)
您可以使用:
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);
答案 1 :(得分:0)
检查上一行是否在Cell中具有不同的值。如果是,则返回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;
}
您应该展开此函数以接受列名作为参数以提高可重用性。过载接受列索引也会派上用场。