问题
I would like to have a condition in one of my Grid-view's column,which it may contains a number string (6-10 digits) or characters (3-6). Something like :
<asp:HyperLink ID="HL_Number" runat="server" Text='<%# Eval("Code")%>' Target="_blank"
NavigateUrl='<%# "http://www.address.com/" + Eval("Code")%>'> Visible='<% (IsNumber(Eval("Code"))==true)? true:false %>'
</asp:HyperLink>
<br />
<asp:HyperLink ID="HL_String" runat="server" Text='<%# Eval("Code")%>' Target="_blank"
NavigateUrl='<%# "~/PDF/" + Eval("Code")+"pdf" %>' Visible='<% (IsNumber(Eval("Code"))==false)? true:false %>'>
</asp:HyperLink>
One of HyperLink must be visible at the same time, how can i perform it? Thanks in Advance.
回答1:
From a good design perspective, move this logic to your business layer. Let's say this is your entity
public class MyEntity
{
public int Id {get;set;}
// ... some other properties
public string Code {get;set;}
// if you need some other control to be visible based on
// whether Code is a number or not, use this to bind to Visible property.
// Note, this is not required in case of HyperLink
public bool IsVisible
{
{ get {return IsNumber(Code); }
}
public string NavigateUrl
{
get { return GetUrl(Code); }
}
private bool IsNumber(string code) { // your method body here }
private string GetUrl(string code)
{
if(!IsNumber(code))
{
return string.Format("~/PDF/{0}pdf", code);
}
return string.Format("http://www.address.com/{0}",code);
}
}
Assuming your datasource is collection of MyEntity objects.
var dataSource = // some method that returns collection of MyEntity objects,
// for example List<MyEntity>
myGridView.DataSource = dataSource;
myGridView.DataBind();
Now, keep only 1 HyperLink control in your GridView and bind it to respective properties.
<asp:HyperLink ID="HL_String" runat="server" Text='<%# Eval("Code")%>' Target="_blank"
NavigateUrl='<%# Eval("NavigateUrl") %>'>
</asp:HyperLink>
来源:https://stackoverflow.com/questions/29367537/embeded-if-statment-in-gridview-component