The GridView is an incredibly versatile control. Most of its power comes from treating every row the same.
Sometimes you want to treat individual rows specially. For example to apply conditional formatting, to only enable Editing for a subset of the rows...
My favorite way is to exploit the fact that the system generated class used to host the page inherits from the class containing you code behind logic. Therefore any code you place in the code behind file can be available in the page. That code can be called from a custom binding expression.
Here is how you might make a row conditionally editable. Our simple logic will make it Editable only when the Employee's ID is an odd number.
Add a GridView to a WebForm and connect it to display rows from the Northwind database Employees table.
Add a CommandButton column.
Now use the Edit Colums function and turn the CommandButton column into a 'templated column'.
Switch to the source view of the page and find the line for the Edit button. Manually add the Enabled property and bind it to a function call PermitEdit. The PermitEdit function will need the Employee ID and it can get that from a call to Eval("EmployeeID). Eval returns an object so the result should be cast to int.
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
Enabled='<%# PermitEdit((int) Eval("EmployeeID")) %>'
Move to the code behind file and add the PermitEdit function. It needs to have protected (or public) access to make it available in the page. It should return bool. Like this...
protected bool PermitEdit(int EmployeeId)
return EmployeeId % 2 == 1;
When you run your page the Edit button will only be available for Employees with an odd Id number.
Clearly you can make the logic in the code behind file as complex as you need and you can apply the same strategy to other, even multiple, properties on the same control.