In a SharePoint webpart I am displaying an SPGridView. The SPGridView control is inside an Ajax updatepanel and is bound to a datatable in the code.
The columns for the gridview are created mostly as templatefields, there is only one boundfield. I have created a class that inherits ITemplate that produces the itemtemplate for the templatefields. This class also handles the databinding of the controls to columns/data in the datatable.
I have a button outside the grid which when clicked is designed to save the changes made to the data in the gridview to the datatable and underlying database.
The problem is that I cannot get a reference to the controls within the gridview in the buttons 'onclick' event, I am iterating through the rows in the gridview and using the following code to obtain a reference to the control:
foreach (SPGridViewRow row in grid.Rows)
{
TextBox txtExamMark = (TextBox)row.FindControl("txtExamMark");
The above is always null and the cast does not work. Can anyone shed any light on this? I assume it is some kind of viewstate issue but im not sure.
I have posted some more code samples below.
Thanks,
Alex
public class CustomSPGridViewTemplate : ITemplate
{
string columnName;
string controlType;
int controlWidth;
ListItemCollection itemColl;
string txtMode;
public CustomSPGridViewTemplate(string ctype,string colname,ListItemCollection itemcol,string mode,int cWidth)
{
columnName = colname;
controlType = ctype;
itemColl = itemcol;
controlWidth = cWidth;
txtMode = mode;
}
public void InstantiateIn(System.Web.UI.Control container)
{
if (controlType == "TextBox")
{
TextBox txtBox = new TextBox();
txtBox.ID = "txt" + columnName;
txtBox.Visible = true;
txtBox.Width = Unit.Pixel(controlWidth);
txtBox.DataBinding += new EventHandler(txtBox_DataBinding);
if (txtMode == "MultiLine")
{
txtBox.TextMode = TextBoxMode.MultiLine;
}
container.Controls.Add(txtBox);
}
if (controlType == "PupilImage")
{
Image pupilImage = new Image();
pupilImage.ID = "pupilImage";
pupilImage.Visible = true;
pupilImage.DataBinding += new EventHandler(pupilImage_DataBinding);
container.Controls.Add(pupilImage);
}
if (controlType == "DropDown")
{
DropDownList dropDown = new DropDownList();
dropDown.ID = "ddl" + columnName;
dropDown.Visible = true;
dropDown.DataBinding += new EventHandler(dropDown_DataBinding);
container.Controls.Add(dropDown);
}
}
void txtBox_DataBinding(object sender, EventArgs e)
{
TextBox txtBox = (TextBox)sender;
SPGridViewRow container = (SPGridViewRow)txtBox.NamingContainer;
txtBox.Text = DataBinder.Eval(container.DataItem, columnName).ToString();
}