views:

74

answers:

2

I have a DataGridView that has MultiSelect = true. After the user selects different cells from different rows how can I get the value of all the selected cells?

is it using a foreach() or a simple build in method?

+1  A: 

foreach -

DataGrid.SelectedCells

More info on the SelectedCells Property can be found at http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.selectedcells.aspx

The SelectedCells collection is inefficient with large selections in DataGridView. There is a method you can use to get the count of the selected cells. iterate based on that and it'll be faster.

for (int i = 0; i < grid.GetCellCount(System.Windows.Forms.DataGridViewElementStates.Selected); i++)
{
    string val = grid.SelectedCells[i].Value;
}
Gabriel McAdams
Can you write a example of the for each?
Y_Y
Added code example for you. Be sure to look at the GetCellCount method. It'll be important to know.
Gabriel McAdams
How do you guys answer so quick? do you check the website every second?
Y_Y
+4  A: 

You can iterate over SelectedCells.

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

You asked only for the value, but you probably also want to know the row and the column of the cell otherwise the value could be meaningless. You can access these also on the cell object.

Mark Byers
I can see you have years programming... Thanks
Y_Y