Search code examples
c#asp.net.netexceptionfindcontrol

Object reference not set to an instance of an object #2


I have got below error message:

Object reference not set to an instance of an object.

Code-behind:

public partial class Edit : System.Web.UI.Page
{
    private TextBox updated_time;

    protected void Page_Load(object sender, EventArgs e)
    {
        updated_time = (TextBox)ABC_DV.FindControl("txt_updated_time");
        updated_time.Text = DateTime.Now.ToString();
    }
}

how could i solve this ?

UPDATED

<asp:DetailsView ID="ABC_DV" runat="server" AutoGenerateRows="False"
        DefaultMode="Edit" DataKeyNames="TYPE_ID" DataSourceID="ABC_EDS">
        <Fields>
            <asp:TemplateField HeaderText="Type Id" SortExpression="TYPE_ID">
                <EditItemTemplate>
                    <asp:TextBox ID="txt_type_id" Width="200" runat="server" Text='<%# Bind("TYPE_ID") %>'></asp:TextBox>
                </EditItemTemplate>
                <InsertItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("TYPE_ID") %>'></asp:TextBox>
                </InsertItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("TYPE_ID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>        
            <asp:TemplateField HeaderText="Updated Time" SortExpression="UDPATED_TIME">
                <EditItemTemplate>
                    <asp:TextBox ID="txt_updated_time" Width="200" runat="server" Text='<%# Bind("UDPATED_TIME") %>'></asp:TextBox>
                </EditItemTemplate>
                <InsertItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("UDPATED_TIME") %>'></asp:TextBox>
                </InsertItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Labe2" runat="server" Text='<%# Bind("UDPATED_TIME") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>            
        </Fields>
    </asp:DetailsView>

Solution

  • Okay you need to take into consideration the mode the DetailsView is in when attempting to access a control, it will not exist in the hierarchy if it isn't in the edit mode causing the Page_Load to explode when it is called without the DetailsView in edit mode. Add some checks to your code to properly handle the control state.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (ABC_DV.CurrentMode == DetailsViewMode.Edit) {
          updated_time = (TextBox)ABC_DV.FindControl("txt_updated_time");
          if(null != updated_time)
            updated_time.Text = DateTime.Now.ToString();
        }
    }