text: Q:
  
  DataGridView selected column value Error in c# (Win Forms)
  
  DataGridView slected column value Error
  I have an exception "Index is out of range. It must be non negative and less than the size of the collection. 
  Parameter name: index ".
  When all the columns set by "gridview.datasouce" (get date from database), code is fine and no any problems.
  (without select column)
  Exception happens only after adding "Select" column.
  when try to get the value of the selected cell then exception appear.
  data table :
  | Id | Name | Qty | Price |
  code as follows:
  //create the grid
  private void fillData()
      {
          try
          {
              DataGridViewCheckBoxColumn select = new DataGridViewCheckBoxColumn();
              select.DataPropertyName = "select";
              select.Name = "select";
              select.HeaderText = "Select";
              select.TrueValue = "1";
              select.FalseValue = "0";
              grd_selectStockEntry.Columns.Add(select);
  
              DataGridViewButtonColumn col = new DataGridViewButtonColumn();
              col.DataPropertyName = "Id";
              col.Name = "Id";
              col.HeaderText = "Id";
              grd_selectStockEntry.Columns.Add(col);
  
              grd_selectStockEntry.DataSource = //get data table from DB           
  
          }
          catch (Exception ex)
          {
              //ex handler
          }
      }
  
  //Grid Cell Content Click
   private void grd_Entry_CellContentClick(object sender, DataGridViewCellEventArgs e)
      {
          var senderGrid = (DataGridView)sender;
  
          try
          {
              if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
              {
                  Id = senderGrid.SelectedCells[e.ColumnIndex].Value.ToString();  //exception occurs in this line
  
              }
          }
          catch (Exception ex)
          {
              //ex handler
          }
      }
  
  A:
  
  I have figured it out.
  something was wrong in the Index of selectedCells.
  changed the following line and then code is fine
  Id = senderGrid.SelectedCells[e.ColumnIndex - 1].Value.ToString();
  
  don't know if the coding style is good or bad.
  
  