Itemdatabound and edititemtemplate

  • Thread starter Thread starter srini.venkatesan
  • Start date Start date
S

srini.venkatesan

I am trying to access a control from edititemtemplate in itemdatabound
event, but I get a run time null reference exception.

Class file :
In Datagrid_update I am able to access with no issues.
DataGridItem item = DataGrid2.Items[DataGrid2.EditItemIndex];
string test= ((TextBox) item.Cells[2].FindControl("xxx")).Text;

In DataGrid2_ItemDataBound , the following line gives me a run time
exception
string test1= ((TextBox) e.Item.Cells[2].FindControl("xxx)).Text;

Part of html:
<asp:TemplateColumn HeaderText="TotalTest">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Totalx") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="xxx" Runat="server" Text='<%#
DataBinder.Eval(Container.DataItem, "Totalx") %>' />
</EditItemTemplate>
</asp:TemplateColumn>

Is edititemtemplate is not accessible from itemdatabound ? Any help is
appreicated.
 
The OnItemDataBoundEvent fires for a lot of elements and containers. That
means that there could be a case were FindControl("xxx") returns null. So
you should test first to see if the return value of FindControl is not null.
You could try this..

TextBox myTextBox = e.Item.Cells[2].FindControl("xxx") as TextBox;
if (myTextBox != null)
{
string test1= ((TextBox) e.Item.Cells[2].FindControl("xxx")).Text;
}

HTH
 
Howdy,

No need to reference cells collection, and the current's item type is
available via ItemType:

protected void DataGrid2_ItemDataBound (object sender, DataGridItemEventArgs
e)
{
DataGridItem item = e.Item;

if (item.ItemType == ListItemType.EditItem)
{
TextBox textBox = (TextBox)item.FindControl("xxx");
string value = textBox.Text;
}
}

Hope this helps
 
Back
Top