Search code examples
c#asp.netgridviewedititemtemplate

Error on Accessing Gridview EditItemTemplate


Below is my Error Message:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

DueDateTB was null.

This happens during execution when I start updating the Date Column in Gridview. Below is my Code for both front and end side.

Back Side:

protected void PaymentsDueGV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
  TextBox DueDateTB = (TextBox)((GridView)sender).FindControl("DueDateTB");
  string DueDate = DueDateTB.Text;
  DueDateTB.Text= (Convert.ToDateTime(DueDateTB.Text)).ToString("dddd, MMMM dd, yyyy h:mm tt");
  PaymentsDueDS.UpdateParameters["DueDate"].DefaultValue = DueDateTB.Text;
}

Front Side:

<asp:TemplateField HeaderText="Due Date" SortExpression="CreatedDate" ItemStyle-HorizontalAlign="Center">
  <EditItemTemplate>
    <asp:TextBox runat="server" Text='<%# Convert.ToDateTime(Eval("DueDate")).ToLocalTime().ToString("d") %>' ID="DueDateTB" CausesValidation="True" Columns="5" MaxLength="10"></asp:TextBox>
      <asp:RequiredFieldValidator ID="DueDateTBRValidator" runat="server" ErrorMessage="*"
           ForeColor="Black" ControlToValidate="DueDateTB">
      </asp:RequiredFieldValidator>
  <asp:CalendarExtender ID="DueDateCE" runat="server" Enabled="True" TargetControlID="DueDateTB" Format="MM/dd/yyyy"></asp:CalendarExtender>
  </EditItemTemplate>
  <ItemTemplate>
      <asp:Label ID="lblLocalTime" runat="server" Text='<%# Convert.ToDateTime(Eval("DueDate")).ToLocalTime().ToString("d") %>'></asp:Label>
  </ItemTemplate>
  <HeaderStyle CssClass="GridCells"></HeaderStyle>
  <ItemStyle CssClass="GridCells"></ItemStyle>
  <FooterStyle CssClass="GridCells"></FooterStyle>
</asp:TemplateField>

Solution

  • You've to cast the sender object into GridViewRow not into GridView as:

    TextBox DueDateTB = (TextBox)((GridViewRow)sender).FindControl("DueDateTB");