2010-07-30 16 views
1

在我的ASP.NET應用程序中,我有一個GridView。對於此GridView中的特定字段,我添加了一個帶有DropDownList的EditItemTemplate。但是,如果該字段的值是「X」,那麼我只想顯示一個標籤而不是DropDownList。那麼我怎樣才能以編程方式檢查字段值,然後決定顯示哪個控件?如何以編程方式確定在我的EditItemTemplate中使用哪個控件? (ASP.NET)

這裏是我的EditItemTemplate:它

<EditItemTemplate> 

<asp:DropDownList ID="DropDownListLevel_ID" runat="server" 
    DataSourceID="ODSTechLvl" DataTextField="Level_Name" 
    DataValueField="Level_ID" SelectedValue='<%# Bind("Level_ID", "{0}") %>'> 
</asp:DropDownList> 

</EditItemTemplate> 

如果Level_ID的值是 「X」,然後我想用:

<asp:Label ID="LabelLevel_ID" runat="server" Text='<%# Bind("Level_ID") %>'></asp:Label> 

,而不是DropDownList的。

我試圖在DropDownList之前嵌入if語句來檢查Eval(「Level_ID」),但這似乎不起作用。有什麼想法嗎?

回答

0

這裏有些東西可以用於ASP.Net。

您可以創建一個RowDataBound事件和隱藏的標籤或將DropDownList

<asp:GridView id="thingsGrid" runat="server" OnRowDataBound="thingsGrid_RowDataBound" 

...> ...

並在後面的代碼:

protected void thingsGrid_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 

     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      var boundData = e.Row.DataItem; 
      ... 
      if (boundDataMeetsCondition) 
      { 
       e.Row.Cells[4].FindControl("editThingDropDownList").Visible = false; 
       e.Row.Cells[4].FindControl("editThingLabel").Visible = true;//* 
      } 
      else 
      { 
       ...  
      } 
     } 
} 

*請注意,這並不理想,因爲它對單元格索引進行了硬編碼,並且這些控件的ID是一個字符串,不會在運行時檢查。在asp.net mvc中有更好的方法來解決這個問題。

OnRowDataBound是一個大錘,它可以讓您完全訪問您的網格,頁面方法和整個應用程序。在一個非常簡單的情況下,您也可以在不涉及代碼隱藏的情況下進行內聯。

<asp:Label ID="Label1" runat="server" Visible='<%# Convert.ToBoolean(Eval("BooleanPropertyInData"))%>' Text='<%# Eval("PropertyInData") %>'></asp:Label>       

<asp:Label ID="Label1" runat="server" Visible='<%# Eval("PropertyInData").ToString()=="specialValue"%>' Text='<%# Eval("PropertyInData") %>'></asp:Label> 
在第一個行內的做法

,您的數據源有揭露這樣的屬性,並在第二個你是硬編碼的specialValue業務邏輯到您的演示,這也是醜陋,並會導致可維護性問題。

1

試試這個:

<EditItemTemplate> 

<asp:DropDownList ID="DropDownListLevel_ID" runat="server" 
    DataSourceID="ODSTechLvl" DataTextField="Level_Name" 
    DataValueField="Level_ID" SelectedValue='<%# Bind("Level_ID", "{0}") %>' 
    Visible='<%# Eval("Level_ID") != "X" %>'> 
</asp:DropDownList> 

<asp:Label ID="LabelLevel_ID" runat="server" Text='<%# Bind("Level_ID") %>' 
    Visible='<%# Eval("Level_ID") == "X" %>'></asp:Label> 

</EditItemTemplate> 
相關問題