Introduction
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.
Using the Code
Here's a quick code snippet on setting the boundfield
column for autogenerated columns in GridView
to ReadOnly
.
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;
}
}
}
GridView
cells are composed of different DataControlFields
and basically AutoGenerated Columns uses a BoundField
for displaying the data. If you have noticed from the code above, we loop through the cells and cast them to a DataControlFieldCell
type to get the ContainingField
. We then cast the ContainingField
to a BoundField
type so that we can check the DataField
used in a particular column.
You could also use the code above if you want to (for example) hide a specific column in your auto generated grid.
But Why Not Just Use This?
GridView1.Columns[index].Visible = false;
Using the code above will give you "index was out of range error". Why? This is because auto generated columns are not added in the GridView
columns collection.
Here's the quick snippet for hiding a specific column:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
foreach (TableCell cell in e.Row.Cells)
{
BoundField field = (BoundField)((DataControlFieldCell)cell).ContainingField;
if (field.DataField == "ColumnName")
{
field.Visible = false;
}
}
}
That's it! I hope someone finds this post useful.