This question was asked from the forums.asp.net and thought I’d blog about it for future reference. The question is “how do we set ReadOnly for autogenerated columns in gridview when it’s on edit mode?”. 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. To make it more clear we’ll create a simple demonstration. Consider that we have this HTML mark-up below:
<asp:GridView ID="GridView1" runat="server"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowcreated="GridView1_RowCreated"
onrowediting="GridView1_RowEditing">
<Columns>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
Now let’s bind the grid with simple data and handle Edit and Cancel events. Here’s the code block below:
private List<Product> GetProducts() {
List<Product> products = new List<Product>();
Product p = new Product();
p.ID = 1;
p.Make = "Samsung";
p.Model = "Galaxy S1";
products.Add(p);
p = new Product();
p.ID = 2;
p.Make = "Samsung";
p.Model = "Galaxy S2";
products.Add(p);
p = new Product();
p.ID = 3;
p.Make = "Samsung";
p.Model = "Galaxy S3";
products.Add(p);
p = new Product();
p.ID = 4;
p.Make = "Samsung";
p.Model = "Galaxy Note";
products.Add(p);
p = new Product();
p.ID = 5;
p.Make = "Apple";
p.Model = "iPhone 4";
products.Add(p);
p = new Product();
p.ID = 6;
p.Make = "Apple";
p.Model = "iPhone 4s";
products.Add(p);
p = new Product();
p.ID = 7;
p.Make = "Apple";
p.Model = "iPhone 5";
products.Add(p);
return products;
}
private void BindGrid() {
GridView1.DataSource = GetProducts();
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
BindGrid();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) {
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {
GridView1.EditIndex = -1;
BindGrid();
}
Running the code will give us this output below:
On initial load

On Edit

As you can see all the columns in a row including the ID column turned to editable. Now let’s go ahead and set the ID column to ReadOnly so that the next time we put the grid in edit mode it will not be editable. Here’s the code below:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) {
foreach (TableCell cell in e.Row.Cells) {
if (!string.IsNullOrEmpty(cell.Text) && cell.Text != " ") {
BoundField field = (BoundField)((DataControlFieldCell)cell).ContainingField;
if (field.DataField == "ID")
field.ReadOnly = true;
}
}
}
Running the code will give us this output below:

That’s it! I hope someone find this post useful!