Tip and Tricks: Accessing AutoGenerated Columns in GridView

I've seen many developers in the forums were asking stuff like “how do we set read-only for autogenerated columns in gridview” or "how to access autogenerated bound columns in GridView". Well as you may know autogenerated columns are created dynamically on the fly and so we need to manually access each columns in the code before we can set their properties. Here's a quick code snippet on setting the boundfield column for autogenerated columns in GridView to ReadOnly.
  1. protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
  2.  {  
  3.             foreach (TableCell cell in e.Row.Cells)
  4.              {  
  5.                 if (!string.IsNullOrEmpty(cell.Text) && cell.Text != " "
  6.                 {  
  7.                     BoundField field = (BoundField)((DataControlFieldCell)cell).ContainingField;  
  8.                     if (field.DataField == "ID")  
  9.                         field.ReadOnly = true;  
  10.                 }  
  11.             }  
  12.   }