我想要做的只有選擇dgvCells是在同一列的東西:做的東西,如果所選單元格是在同一列
foreach (DataGridViewCell c in dgvC.SelectedCells)
if (c.ColumnIndex is the same) // how to say this ?
我想要做的只有選擇dgvCells是在同一列的東西:做的東西,如果所選單元格是在同一列
foreach (DataGridViewCell c in dgvC.SelectedCells)
if (c.ColumnIndex is the same) // how to say this ?
看了一段時間沒有答覆,這裏是我的解決方案,我不認爲它不夠優化,但我認爲它會做的工作
int columnIndex = dgvC.SelectedCells[0].ColumnIndex;
bool sameCol = true;
for(int i=0;i<dgvC.SelectedCells.Count;i++)
{
if(dgvC.SelectedCells[i].ColumnIndex != columnIndex)
{
sameCol = false;
break;
}
}
if (sameCol)
{
MessageBox.Show("Same Column");
}
else
{
MessageBox.Show("Not same column");
}
Ë DIT: 您也可以嘗試:
int columnIndex = dgvC.SelectedCells[0].ColumnIndex;
if (dgvC.SelectedCells.Cast<DataGridViewCell>().Any(r => r.ColumnIndex != columnIndex))
{
//Not same
}
else
{
//Same
}
一些基本的東西像這應該工作:
Boolean allCells = true;
int colIndex = dgvC.SelectedCells[0].ColumnIndex;
foreach (DataGridViewCell c in dgvC.SelectedCells)
{
if(c.ColumnIndex != colIndex)
{
allCells = false;
}
}
if(allCells)
{
//do stuff here
}
可以使用的GroupBy以確保細胞是從同一列
if(dgvC.SelectedCells.Cast<DataGridViewCell>()
.GroupBy(c => c.ColumnIndex).Count() == 1)
{
foreach (DataGridViewCell c in dgvC.SelectedCells)
//your code
}
試試這一個。
for (int i=0; i < dgvC.SelectedCells.Count; i++)
{
int currentCellColumnIndex = dgvC.SelectedCells[i].ColumnIndex;
for (int j=i+1; j < dgvC.SelectedCells.Count-1; j++)
{
if(currentCellColumnIndex == dgvC.SelectedCells[j])
{
//Same column
//dgvC.SelectedCells[i] and all dgvC.SelectedCells[j] have same column
}
}
}
好吧,我會試試這個。謝謝大家。 – Buena
@Buena,不客氣 – Habib