2015-03-31 30 views
0

我想在我的一個Grid-view的列中包含一個數字字符串(6-10位數)或字符(3-6)。例如:在gridview組件中嵌入IF語句

<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> 

HyperLink之一必須在同一時間可見,我該如何執行它?提前致謝。

回答

0

從良好的設計角度出發,將此邏輯移至您的業務層。假設這是你的實體

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); 
    } 
} 

假設你的數據源是MyEntity對象的集合。

var dataSource = // some method that returns collection of MyEntity objects, 
        // for example List<MyEntity> 
    myGridView.DataSource = dataSource; 
    myGridView.DataBind(); 

現在,在GridView中只保留1 HyperLink控件並將其綁定到相應的屬性。

<asp:HyperLink ID="HL_String" runat="server" Text='<%# Eval("Code")%>' Target="_blank" 
       NavigateUrl='<%# Eval("NavigateUrl") %>'> 
</asp:HyperLink>