title: List to Array : Row, Column Indices of Selected Cells in Datagrid
body: <p>I have list of selected cells, I want them to be converted to array so that I can save it.
  I am converting list in an array so that I can get indices of all selected cells (column wise in a row) so that I can retrieve later to fill same cells.</p>
  
  <p>Problem is since cells can be selected in random way i.e I can select row 1 column 1,2,3,7,8,9 leaving column 4,5,6 unselected. As soon as I encounter unselected indices I get "<strong>The Index was out of range</strong>"  error.
  Same error occur if I select some thing in middle of data grid i.e not selecting column at start like column 1,2,3 but selecting row 5 column 5,6,7.</p>
  
  <p>May be some one can help in this or may be point to some other efficient way of doing same task.</p>
  
  <pre><code>List&lt;DataGridViewCell&gt; selectedCells = new List&lt;DataGridViewCell&gt;();
  
  private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
  {
      DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
      if (selectedCells.Contains(cell) ) selectedCells .Remove(cell);
      else selectedCells .Add(cell);
      cell.Style.BackColor = selectedCells .Contains(cell) ? Color.Pink : Color.White;
  }
  
  private void buttonSaveButton_Click(object sender, EventArgs e)
  {
      string [,] selectedcellsArray = new string[dataGridView1.Rows.Count, dataGridView1.Columns.Count];
      int i = 0;
      int j = 0;
      foreach (DataGridViewRow row in dataGridView1.Rows)
      {
          while (j &lt; dataGridView1.Columns.Count)
          {
              selectedcellsArray[i, j] = selectedCells[j].ColumnIndex.ToString();
              j++;
          }
  
          j = 0;
          i++; //next row
      } 
      //some more code
  }
  </code></pre>
  
  <p><img src="https://i.stack.imgur.com/N90bm.jpg" alt="enter image description here"></p>