squarer
squarer

Reputation: 25

How to find FormView within GridView EmptyDataTemplate

I have a GridView contains Formview like:

<asp:GridView ID="gv1" runat="server" AutoGenerateColumns="false"
     OnRowCommand="gv1_RowCommand" DataKeyNames="employeeID"
     DataSourceID="ds">
   <EmptyDataTemplate>
       <asp:FormView ID="fv1" runat="server" DataKeyNames="employeeID" 
                     DataSourceID="ds" DefaultMode="Insert">
           <InsertItemTemplate>
               // insert mode table
           </InsertItemTemplate>
           <EditItemTemplate>
              //  edit mode table
           </EditItemTemplate>
      </asp:FormView>
   </EmptyDataTemplate>

   <Columns>
       <asp:TemplateField>
       <HeaderTemplate>
           <asp:Button ID="btnNew" runat="server" Text="New Record" CommandName="New" />
       </HeaderTemplate>
           <ItemTemplate>
           <asp:Button ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" />
       </ItemTemplate>
       </asp:TemplateField>
   </Columns>
</asp:GridView>

What I want is when the button been clicked, then page displays the EmptyDataTemplate, so in codebehind I try:

protected void gv1_RowCommand(object sender, GridViewCommandEventArgs e) {
    switch(e.CommandName){
        case "New":
            gv1.DataSourceID = null;
            break;
        case "Edit":
            var row = ((Control)e.CommandSource).NamingContainer as GridViewRow;
            if (row != null) {
                var fv = row.FindControl("fv1") as FormView;
                fv.ChangeMode(FormViewMode.Edit);
            }
            gv1.DataSourceID = null;
            break;
    }
}

But I stuck in getting FormView, it occurs NullReferenceException error. Any suggestion is appreciated.

Upvotes: 0

Views: 948

Answers (2)

Zo Has
Zo Has

Reputation: 13038

EmptyDataTemplate is used when datasource returns zero records. It is used for displaying messages such as 'No records' found'. If you want to databind a control use a Templatefield & fetch control using FindControl on RowDataBoundEvent.

Upvotes: 0

Ann L.
Ann L.

Reputation: 13965

I believe that the EmptyDataTemplate only shows when you have bound to a data source and there are no records in the source. So if you have any records, your EmptyDataTemplate will never show. And I don't believe the columns with the command buttons will show when the data source is empty, either, so what you're attempting to do cannot be done in that way.

Some people provide add-record functionality by using the grid footer as a place to add a new row. Here's a Stack Overflow question and answer (with an example) of how to do it:

ASP.net GridView not Inserting from Footer Template

Upvotes: 1

Related Questions