I have a gridview which displays some details about certain files. It has 5 columns including a template field which contains checkboxes.
From the code behind, OnInit, I add a number of columns for additional information which may or may not be needed depending on the page. Code is below:
for (int i = 0; i < models.Length && i < 3; i++)
{
var model = models[i];
//Add gridview rows
BoundField bf = new BoundField();
bf.DataField = "Attribute" + i;
bf.HeaderText = model.AttributeName;
bf.Visible = true;
gvFiles.Columns.Insert(6 + i, bf);
}
This works well and I get the columns. In the OnLoad event I databind certain data to the gridview and that works as well.
The problem rises when a postback occurs. Whenever the page creates a postback, it performs OnInit, then crashes with this ('on page') error message:
An error has occurred because a control with id 'ctl00$MainContent$gvFiles$ctl02$ctl00' could not be located or a different control is assigned to the same ID after postback. If the ID is not assigned, explicitly set the ID property of controls that raise postback events to avoid this error.
I identified the control which was giving the issue as the checkbox in the TemplateField, and I gave it an id. However now, on postback the following happens:
The checkbox in the TemplateFieldss don't appear
One of the columns is an ImageField and it loses its "Control-Style Width/Height" parameters and I get massive images.
The issue is only happening on postback, and removing the code which adds the columns pro grammatically makes everything work perfectly.
How can I get this to work ?