Yesterday i was struggling with GridView I need to check some if..else logic and based on it have to show values in Grid..I am checking it in Eval if else but can’t get succeeded because if..else is not supprted with Eval..then how i have achieved it..its concept of “Binding Grid with functions”. Let us see..
Problem:
On binding of Grid i want to check that if entityCount>1 then have to show that value in grid with HyperLink which points to some page else show Plain Text in grid..
I was trying this one[Which won't work]
<asp:TemplateField HeaderText=”Def Price”>
<ItemTemplate>
<%# if Eval(“entityPriceCountField”) > 1%>
<asp:HyperLink ID=”lnkentityPrice” Text=’<%# Eval(“entityPriceField”) %>’ runat=”Server” Target=”_blank” NavigateUrl=”#”/>
<%# else %>
<asp:Label ID=”lblentityPrice” Text=’<%# Eval(“entityPriceField”) %>’ CssClass=”SearchBookingsLabelStyle” runat=”Server” />
</ItemTemplate>
</asp:TemplateField>
NOTE: You can’t write like this.
Solution:
I had its solution:
1. Binded my grid with function in my .aspx.cs file.
this function check count if count>1 then text will be in hyper link else show plain text.
2. Called it witin my Grid.
Here it is:
.aspx page
<asp:TemplateField HeaderText=”Def Price”>
<ItemTemplate>
<asp:Label ID=”entityPrice” Text=’<%# GetEntityPriceText((double)Eval(“entityPriceField”),(int)Eval(“entityPriceCountField”))%>’ CssClass=”SearchBookingsLabelStyle” runat=”Server” />
</ItemTemplate>
</asp:TemplateField>
.aspx.cs code
protected string GetEntityPriceText(Nullable<double> entityprice,Nullable<int> entityPriceCount)
{
//If count>1 then show text in HyperLink
string labelText = string.Empty;
if (entityPriceCount > 1)
labelText = “<a href=MyPage.aspx’>” + entityprice.ToString() + “</a>”;
else
labelText = entityprice.ToString();
return labelText;
}
It worked like a chram!!!