6

我有一个具有 MultiSelect = true 的 DataGridView。用户从不同行中选择不同的单元格后,如何获取所有选定单元格的值?

4

2 回答 2

16

您可以遍历SelectedCells

foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
    MessageBox.Show(cell.Value.ToString());
}

您只询问了值,但您可能还想知道单元格的行和列,否则该值可能毫无意义。您也可以在单元对象上访问这些。

于 2009-12-30T04:33:44.723 回答
4

前锋——

DataGrid.SelectedCells

有关 SelectedCells 属性的更多信息,请访问http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.selectedcells.aspx

SelectedCells 集合对于 DataGridView 中的大量选择效率低下。您可以使用一种方法来获取所选单元格的计数。在此基础上进行迭代,它会更快。

for (int i = 0; i < grid.GetCellCount(System.Windows.Forms.DataGridViewElementStates.Selected); i++)
{
    string val = grid.SelectedCells[i].Value;
}
于 2009-12-30T04:23:18.167 回答