How to Get the Selected Cells and Rows in the Windows Forms DataGridView Control

Here I am showing how to get selected cells/rows in DataGridView Control and basically use of IEnumerator while accessing them. In the following code, dataGrid_ZipList is DataGridView Control. We store all the selected rows into a DataGridViewSelectedRowCollection object. Then we put them in an enumerator and iterate the collection one by one and keep on adding the one cell item (Postal Code in this case) of selected row into a List (say lstPostalCodes).


DataGridViewSelectedRowCollection SelectRowsSet = dataGrid_ZipList.SelectedRows;

DataGridViewRow row;

IEnumerator Enumerator = SelectRowsSet.GetEnumerator();

Enumerator.Reset();        

while (Enumerator.MoveNext())

{

      row = (DataGridViewRow)Enumerator.Current;

      lstPostalCodes.Add(row.Cells["POSTAL_CODE"].Value.ToString());                        

}