2009-09-02 35 views
1

在本週之前,我從來沒有在我的生活中寫過一縷ASP.NET,所以請在我身上輕鬆一下。檢查ASP Repeater控件中的空數據庫值

我有一個ASP.NET頁面顯示來自數據庫的圖片。我創建一個SqlDataReader並將轉發器綁定到這個閱讀器。該頁面顯示一個包含三列的表格:pic的縮略圖(來自數據庫的路徑),照片的拍攝名稱(來自數據庫)以及有關照片的註釋。

當我上載圖片到數據庫時,評論將爲空。我希望表格顯示註釋(如果存在),或者註釋字段在數據庫中爲空,則顯示ASP文本框和按鈕以供用戶輸入關於圖片的註釋。

事實證明這並不像我想象的那麼容易。任何人都可以建議我:

A)的明確的測試以確定是否該行的「註釋」一欄爲空

B)如何有條件地顯示任何文本或文本框/按鈕組合(有texbox來自數據庫的「ID」列的ID)

我相信我有技巧來編寫按鈕點擊處理程序來更新數據庫與評論...如果我能得到它顯示。

非常感謝,並承諾未來會拒絕ASP.NET項目!

回答

2

由於您處於數據綁定上下文中,因此可以在佔位符(或任何其他控件)的可見屬性上使用數據綁定表達式。

<asp:PlaceHolder runat="server" visible='<%# Convert.IsDbNull(Eval("comment"))%>'> 
    <asp:TextBox ID="txtNewComment"... /> 
    <asp:Button ... /> 
</asp:PlaceHolder> 

對於not null,只需要拍一下「Convert」的exclaimation point,它會顯示它何時不是null。

至於對clickHandler,因爲「發件人」將是按鈕,你總是可以做一個簡單的

((Button)sender).Parent.FindControl("txtNewComment") 

,你有你的文本框。

0

如果註釋字段在數據庫中包含NULL值,則可以使用Alex的建議來顯示註釋或文本框/按鈕組合。我想你需要綁定到'OnItemCommand'來處理中繼器中的按鈕點擊。

下面是一個例子。

<asp:Repeater ID="myRepeater" runat="server" OnItemCommand="myRepeater_ItemCommand"> 
    <HeaderTemplate> 
     <table> 
    </HeaderTemplate> 
    <ItemTemplate>   
     <tr> 
      <td> 
       <asp:Image ID="imgThumbNail" runat="server" ImageUrl='<%# Eval("path") %>' /> 
      </td> 
      <td> 
       <asp:Label ID="lblCamera" runat="server" Text='<%# Eval("camera") %>'></asp:Label> 
      </td> 
      <td> 
       <asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible='<%# Convert.IsDBNull(Eval("comment"))%>'> 
        <asp:Button ID="btnAddComment" runat="server" CommandArgument='<%# Eval("id") %>' CommandName="AddComment" Text="Add Comment" /> 
        <asp:TextBox ID="txtComment" runat="server" </asp:TextBox>      
       </asp:PlaceHolder>    
       <asp:PlaceHolder ID="PlaceHolder2" runat="server" Visible='<%# !Convert.IsDBNull(Eval("comment"))%>'> 
        <asp:Label ID="lblComment" runat="server" Text='<%# Eval("comment") %>'></asp:Label> 
       </asp:PlaceHolder> 
      </td> 
     </tr> 
    </ItemTemplate> 
    <FooterTemplate> 
     </table> 
    </FooterTemplate> 
</asp:Repeater> 

protected void myRepeater_ItemCommand(object source, RepeaterCommandEventArgs e) 
{ 
    if (e.CommandName == "AddComment") 
    { 
     TextBox txtComment = (TextBox)e.Item.FindControl("txtComment"); 
     int id = Convert.ToInt32(e.CommandArgument); 
     // use the record id to update the comment in the database with the value contained in the txtComment.Text property here 
    } 
}