Search code examples
asp.netdetailsviewtemplatefield

ASP.NET DetailsView changing field display for edit verses insert mode


For ASP.NET, I'm using a DetailsView for insert and edit of a record. For edit mode I don't want to display the primary key field because it should not be changed. For insert mode, I want to display the primary key field because it doesn't exist and the user can specify it via a DropDownList that insures they will pick an unique value. A TemplateField is used in the DetailsView markup for the primary key field (hence the DropDownList for insert mode).

My problem is that I cannot get the primary key field to not display for edit mode and to display for insert mode. In the markup I have:

<asp:TemplateField HeaderText="name" InsertVisible="True" Visible="True">
    <InsertItemTemplate>
        <asp:DropDownList ID="ddl2NonMembers" runat="server"
            Width="155px" 
            Sourceless="sqlNonMembers" 
            DataTextField="name" 
            DataValueField="id_adm" 
            SelectedValue='<%# Bind("member_grp") %>'>
        </asp:DropDownList>
    </InsertItemTemplate>
</asp:TemplateField>

With the TemplateField Visible="True", the HeaderText="name" always displays which I don't want for edit mode. With the TemplateField Visible="False", the field never displays which I don't want for insert mode.

How can I achieve the display behavior I want for insert verses edit mode. I'm fine with changing some property programmatically rather than relying an a pure markup approach, but I can't figure out the solution.

Please advise!


Solution

  • you can test the Details View Mode and see if it's in -Edit- mode. You can then hide the DropDownList programmatically.

    if (myDetailsView.CurrentMode == DetailsViewMode.Edit) 
    {
        DropDownList ddl2NonMembers = (DropDownList)myDetailsView.FindControl("ddl2NonMembers");
        ddl2NonMembers.Visible = false;
    }
    

    Also, you can hide the entire column, but you'll need to know the index of that column. Assuming column index is #5 you can do something like:

    if (myDetailsView.CurrentMode == DetailsViewMode.Edit) 
    {
        myDetailsView.Columns[5].Visible = false;
    }
    

    And finally, you can create a function in Code-Behind which checks the current value of the DetailsView and assign it to the Visible property of your Template field:

    public bool showPKField() {
        bool result = true;
        if(myDetailsView.CurrentMode == DetailsViewMode.Edit)
            result = false;
        return result;
    }
    

    And inside your Template Field:

    <asp:TemplateField HeaderText="name" InsertVisible="True" Visible='<%# showPKField() %>'>