How to disable "Edit" button in Gridview?

ognale88 picture ognale88 · Aug 5, 2013 · Viewed 10.4k times · Source

Iam using Item Template field in my gridview to update the values inside particular column. The ItemTemplate field contains "label" control and EditItemTemplate contains "DropDownList". Now the problem is I need to disable the "Edit" button based on the value of "Label"... Attached the lines of coding. Can anyone give me a solution.

Home.Aspx:
**********
   <Columns>

                    <asp:BoundField DataField="Date" HeaderText="Date" ReadOnly="true" />
                    <asp:BoundField DataField="Type" HeaderText="Type" ReadOnly="true" />
                    <asp:BoundField DataField="Reason" HeaderText="Reason" ReadOnly="true" />
                    <asp:BoundField DataField="Request By" HeaderText="Request By" ReadOnly="true" />
                    <asp:TemplateField HeaderText="Status" HeaderStyle-HorizontalAlign="center">
                        <EditItemTemplate>
                            <asp:DropDownList ID="ddlState" AutoPostBack="false" runat="server">
                                <asp:ListItem Text="Approved" Value="Approved">  </asp:ListItem>
                                <asp:ListItem Text="Declined" Value="Declined">  </asp:ListItem>
                                <asp:ListItem Text="Pending" Value="Pending">  </asp:ListItem>
                            </asp:DropDownList>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblName" runat="server" Text='<%# Bind("Status") %>'></asp:Label>
                        </ItemTemplate>
                        <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
                    </asp:TemplateField>
                    <asp:CommandField ShowEditButton="True" />
                </Columns>

Here in my coding "lblName" has the status value in ItemTemplate and "ddlState" has the status value in EditItemTemplate. Based upon the "lblName" value , "Edit" option has to be enabled...

Answer

Garrison Neely picture Garrison Neely · Aug 5, 2013

Convert your Edit CommandField to a TemplateField.

In the newly-generated Button, add the following markup:

Enabled='<%# IsEditEnabled(Eval("Status")) %>'

In your code-behind, create a new method:

protected bool IsEditEnabled(string statusValue)
{
    // Here is where you determine the value
}

Let me know how that works for you.