How to get rows collection based on selected cells in DatagridView

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-07 08:10:25

问题


I have a DatagridView control on a Windows form. It's selectionMode property is set to CellSelect.
I want to operate on DatagridViewRow based on selected cells. The DataGridView control is bound to a DataSource.

How to get the Row collection based on selected cells ?


回答1:


List<DataGridViewRow> rowCollection = new List<DataGridViewRow>();

foreach(DataGridViewCell cell in dataGridView.SelectedCells)
{
    rowCollection.Add(dataGridView.Rows[cell.RowIndex];
}



回答2:


The answer provided as Linq does not work with the syntax provided. Datagridview does not support ienumerable so you have to use:

        IEnumerable<DataGridViewRow> selectedRows = dgPOPLines.SelectedCells.Cast<DataGridViewCell>()
                                           .Select(cell => cell.OwningRow)
                                           .Distinct();



回答3:


DataGridView.SelectedCells will give you the list of cells that are selected. Each of the DataGridViewCell instances in that collection has an OwningRow, this allows you to build your own row collection.

For example:

using System.Linq;

IEnumerable<DataGridViewRow> selectedRows = dgv.SelectedCells
                                               .Select(cell => cell.OwningRow)
                                               .Distinct();


来源:https://stackoverflow.com/questions/8921848/how-to-get-rows-collection-based-on-selected-cells-in-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!