Conditional Formatting for GridView TemplateField & Data Binding

Posted: August 24, 2011 in ASP.Net

Sometimes you may have the need to show conditional formatting for a GridView TemplateField. You can do this in a few ways but I find conditional formatting works best for me. In this example we will look at hiding or showing a TemplateField based on a value that is retrieved from the database:
So now you can use it as follows:
ASPX Page

<asp:GridView ID="gvGridView" runat="server" AutoGenerateColumns="False" >
  <Columns>
    <asp:TemplateField HeaderText="View" ItemStyle-HorizontalAlign="Center">
      <ItemTemplate>
        <asp:LinkButton ID="lbtnLinkButton" runat="server" CommandArgument='<%#Eval("MyValue") %>' CommandName="Select" Visible='<%# ShowField((String)Eval("MyValue")) %>'></asp:LinkButton>
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</GridView>

You will need to add the function ShowField in the code behind page as follows:
Code Behind

public Boolean ShowField(string DBValue)
    {
        if (DBValue == "Show")
        {
            return true;
        }
        else
        {
            return false;
        }
    }

And that is basically it!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s