Search

Custom Search

Monday, March 31, 2008

Conditionally add a control on Markup during Databinding

There are cases that we want to add a control conditionally if the field agrees on some condition. This is common on dataaware controls were we present our data. I come accross with this problem where I need to render a Hyperlink button when HistoryId is not null in the database. We usually write the code to bind controls like as follows:

<asp:LinkButton CommandName = '<%#
string.Format("History{0}",Eval("CustomerHistoryId")) %>' runat= "server"
OnClick= "ViewCustomerHistory"> View ... </asp:LinkButton>


The following code above will just add linkbutton controls on all records fetch, but this is not the desired output. What I did is to use tertiary operator and set the style to none if HistoryId is null. The code below shows how I did it:

<asp:LinkButton CommandName = '<%#
string.Format("History{0}",Eval("CustomerHistoryId")) %>' runat= "server"
Style ='<%# Eval("CustomerHistoryId").ToString() == "" ? "Display:None"
: "Display:Inline"%>'
OnClick= "ViewCustomerHistory"> View ...
</asp:LinkButton>

No comments:

Post a Comment

Adsense Banner