It is best to implement the OnDataBinding method for Button in TemplateColumn .
For instance:
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:Button runat="server" ID="btnDelete" CommandName="Delete" Text="Delete" OnDataBinding="btnDelete_DataBinding" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
Then in your code, follow your logic:
protected void btnDelete_DataBinding(object sender, System.EventArgs e) { Button btn = (Button)(sender); btn.Enabled = !Eval("TheFieldInYourDataSourceToCompare").ToString().Equals("NA"); }
An advantage for this in this regard over other published answers:
- There is no code in your markup
- The code is localized in the
Button control and can be reused if other Buttons require the same functionality. - Comparison with the value of the
DataSource , not the visual result (this may be due to business logic for both rendering and validation).
Hope this helps.
source share