I had to figure this out today so I’m sharing in case someone has the same problem. If you’re trying to use GridView.Columns.RemoveAt(0) to drop the AutoGenerate Link Column at runtime and it’s not working you likely need to rewire the AutoGenerate Command.
Originally, I had initialized the property directly in the GridView Control setup and this usually meets my needs. A feature I am implementing in my application should not offer Editing to Users in a certain Roles, thus I need control of removing this field at runtime.
What I discovered is that the Column position is not 0 when assigning AutoGenerateEditButton in the Control setup. It’s actually -1 and GridView.Columns.RemoveAt(-1) will throw an exception because it’s a negative number.
So, to remove the AutoGenerate Edit Link from the GridView at Runtime I did the following:
- Remove AutoGenerateEditButton=”true” from the <asp:grid view control setup.
- Added an <asp:CommandField with true values for ShowEditButton and ShowCancelButton
Once those two items were accomplished I was able to successfully remove the Edit link at runtime using GridView.Columns.RemoveAt(0).