2009-08-26 86 views
2

好的我有一個GridView,並有一列,如果文件存在,我想成爲一個鏈接,否則我只是希望它是一個標籤。現在,我正在使用參數中傳遞的行更改RowDataBound事件處理函數上的控件。我不是很喜歡這個,因爲我很難編碼列ID,如果它改變了,我將需要記住改變這個代碼。我希望我可以在asp代碼中做一個條件來添加一個鏈接,如果一個屬性值不是null,否則添加一個標籤。這可能嗎?任何不同的解決方案ASP.NET GridView ItemTemplate

我想是這樣的:

<asp:TemplateField HeaderText="Status"> 
    <ItemTemplate> 
    <%# if (Eval("LogFileName") == null) 
    <%#{ 
      <asp:LinkButton ID="LogFileLink" runat="server" CommandArgument='<% #Eval("LogFileName") %>' CommandName="DownloadLogFile" Text='<%# Blah.NDQA.Core.Utilities.GetEnumerationDescription(typeof(Blah.NDQA.Core.BatchStatus), Eval("Status")) %>'> 
    <%# } 
    <%# else 
    <%#{ 
      <asp:Label ID="LogFileLabel" runat="server"Text='<%# Blah.NDQA.Core.Utilities.GetEnumerationDescription(typeof(Blah.NDQA.Core.BatchStatus), Eval("Status")) %>'> 
      </asp:Label> 
    </ItemTemplate> 
</asp:TemplateField> 

回答

2

toyour代碼,如果你要做這個很多,我建議寫你自己的領域。最簡單的方法可能是從HyperlinkField繼承一個NullableHyperlinkField,並且如果錨點的URL否則爲空,則會呈現一個純字符串。

3

您可以繼續使用RowDataBound事件,但在你的aspx添加:

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder> 

在你的C#代碼類似的東西:

if (LogFileName) { 
    LinkButton ctrl = new LinkButton(); 
    ctrl.CommandArgument= ...; 
    ctrl.CommandName= ...; 
} else { 
    Label ctrl = new Label(); 
    ctrl.Text= ...; 
} 

// You have to find the PlaceHolder1 
PlaceHolder1.Controls.Add(ctrl); 

通過這種方式,您不必對列ID進行硬編碼

2

在頁面上使用屬性來確定是否要顯示標籤或鏈接

<asp:GridView ID="gv" runat="server"> 
     <Columns> 
      <asp:TemplateField HeaderText="Status"> 
       <ItemTemplate> 
        <asp:LinkButton runat="server" Visible='<%# ShowLink %>' PostBackUrl="~/Aliases.aspx" >This is the link</asp:LinkButton> 
        <asp:Label runat="server" Visible='<%# ShowLabel %>'>Aliases label</asp:Label> 
       </ItemTemplate> 
      </asp:TemplateField> 
     </Columns> 
    </asp:GridView> 

該添加的屬性ShowLink和ShowLable背後

public bool ShowLabel 
    { 
     get 
     { 
      //determine if the label should be shown 
      return false; 
     } 
     private set 
     { 
      //do nothing 
     } 
    } 
    public bool ShowLink 
    { 
     get 
     { 
      //determine if the link should be shown 
      return true; 
     } 
     private set 
     { 
      //do nothing 
     } 
    } 
+0

我也想到了這一點......只是不真的想將數據添加到我的模型中。 – CSharpAtl 2009-08-26 19:25:19

3

我知道這是有點老了,但爲了以防萬一別人絆倒過這個像我一樣在尋找一個答案,一個類似的問題時,我發現你可以做這樣的事情:

<ItemTemplate>      
    <asp:ImageButton ID="btnDownload" runat="server" 
    CommandName="Download" 
    CommandArgument='<%# Eval("Document_ID") & "," & Eval("Document_Name") %>' 
    ImageUrl="download.png" ToolTip='<%#"Download " & Eval("Document_Name") %>' 
    Visible='<%# Not(Eval("Document_ID") = -1) %>' /> 
</ItemTemplate> 

即設置Visible屬性以根據您的字段評估布爾表達式。如果您想顯示某些內容而不是下載鏈接或按鈕,例如「不可用」標籤,那麼您只需將其Visible屬性設置爲與您的下載鏈接相反的布爾表達式即可。 (這是VB.NET而不是C#,但你明白了。)

相關問題