I recently ran into a challenge where I needed to change the way a asp:Hyperlinkfield control worked based on another value in my database. In my case below. I needed the Gridview to show a link to companyprofile.aspx using the HyperlinkField control if the company was in the Fortune 1000. If the company was not the in the Fortune 1000, then I just needed to display a regular bound field in the Gridview.
To summarize:
If company is in the Fortune 1000, show this field.
<asp:HyperLinkField
DataTextField="CompanyName"
SortExpression="CompanyName"
DataNavigateURLFields="CompID"
DataNavigateURLFormatString="companyprofile.aspx?CompID={0}"
HeaderText="Name" >
</asp:HyperLinkField>
Otherwise, show this field:
<asp:BoundField HeaderText="Name" DataField="CompanyName" SortExpression="CompanyName" />
The way I ended up solving this was to create both a HyperLink control and a Label control and stick them within a TemplateField. With both of the controls within the field, then you can apply a conditional statement within the Visible property of each control. Then, only one control will display at a time, depending on the conditional result. In the code example below, I show both the Hyperlink control and a label control populated with the company name. I then make the 'visible' property conditional on the value of IndexFortune making sure to use logic so that both would never be shown at the same time.
<asp:templatefield headertext="Name" sortexpression="CompanyName">
<itemtemplate>
<asp:hyperlink id="HyperLink1" runat="server" navigateurl='<%# Eval("CompID", "companyprofile.aspx?CompID={0}") %>'
text='<%# Eval("CompanyName") %>' visible='<%# Convert.ToInt32(Eval("IndexFortune")) < 1001 %>' />
<asp:label id="label1" runat="server" text='<%# Eval("CompanyName") %>' visible='<%# Convert.ToInt32(Eval("IndexFortune")) >= 1001 %>' />
</itemtemplate>
</asp:templatefield>
This approach worked well except for one glitch. When the IndexFortune value was null, I would get an error trying to convert this value to an Int32. I addressed this part in my stored procedure using the ISNULL function in SQL Server. When IndexFortune is null, give it a default value of 1001 so it shows up in my label control in the Gridview without a hyperlink.
SELECT ISNULL(IndexFortune, 1001) AS IndexFortune