2011-04-03 62 views
0

我在checkout.aspx頁面有一個div。是div的內容如下:在aspx頁面設置div的可見性問題

<div id="PaymentDetails" runat="server" style="text-align:center" visible="true"> 
    <asp:Label ID="PaymentDetailsLbl" Text="Payment Details:" runat="server" Font-Size="Large"></asp:Label> 
    <br /> 
    <br /> 
    <br /> 
    <asp:Label ID="UNameLbl" Text="User Name:" runat="server"></asp:Label> 
    &nbsp; 
    <asp:Label ID="UNameTextLabel" runat="server" Width="150px"></asp:Label> 
    <br /> 
    <br /> 
    <asp:Label ID="AmountLbl" Text="Amount:" runat="server"></asp:Label> 
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
    <asp:Label ID="AmountTextLabel" runat="server" Width="50px"></asp:Label> 
    <br /> 
    <br /> 
    <asp:Label ID="CCNumberLbl" Text="Credit Card No:" runat="server"></asp:Label> 
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
    <asp:TextBox ID="CCNumberTBox" runat="server"></asp:TextBox> 
    <br /> 
    <br /> 
    <br /> 
    <asp:Button ID="SubmitBtn" runat="server" Text="Submit" OnClick="SubmitBtn_Click" /> 
    <asp:Button ID="ResetBtn" runat="server" OnClick="ResetBtn_Click" Text="Reset" /> 
    <br /> 
    <br /> 
    <asp:Label runat="server" ID="SuccessMessageLabel" ForeColor="Red"></asp:Label> 
    <asp:Button ID="SoftwareDownloadsBtn" runat="server" Text="Software Downloads" Visible="false" 
     OnClick="SoftwareDownloadsBtn_Click" /> 
    <br /> 
    <br /> 
    <asp:RegularExpressionValidator ID="CCNumberValidator" ErrorMessage="Credit Card Number: Min 10 and max 16 digits, starts with 3 or 4" 
     ControlToValidate="CCNumberTBox" runat="server"></asp:RegularExpressionValidator> 
</div> 

,我嘗試當用戶沒有選擇任何產品或用戶已經刪除了使用此代碼的購物車中的所有項目設置DIV假的可見性:

else if ((Session["SelectedRowItems"] == null) || (shoppingCartItems.Count == 0)) 
     { 
      this.Page.FindControl("PaymentDetails").Visible = false; 
      GridView1.EmptyDataText = "No Items Checked Out"; 
      GridView1.EmptyDataRowStyle.CssClass = "EmptyGridViewContent"; 
     } 

但我發現了以下錯誤:未設置爲一個對象的實例

對象引用。

錯誤的詳細截圖here

BTW我使用VS 2008,asp.net/C#其Web應用程序項目

請幫助我。

感謝預期

回答

5

使用FindControl()定位PaymentDetails只有PaymentDetails是根容器的一部分工作。也就是說,它不會遞歸搜索其他控件的子控件。

看起來FindControl()返回null,當您嘗試調用null上的方法時出現錯誤。

FindControl()在這裏是不必要的。只需使用PaymentDetails.Visible = false

+0

請問能告訴我根容器是什麼意思?如果可能,請舉例說明,因爲這會增強我的理解力,並阻止我再次犯同樣的錯誤。預計感謝 – 2011-04-03 18:11:46

+0

@ user653622:有關於此問題的討論[此處](http://forums.asp.net/t/1107107.aspx/1?Solu​​tion+to+the+FindControl+problem)和[here]( http://stackoverflow.com/questions/4393656/how-to-find-control-on-page-by-id)。 – 2011-04-03 18:16:12

+0

非常感謝!這非常有幫助!祝你今天愉快 !! – 2011-04-03 19:00:02

0

如果你的div既不是子頁面,也不是用戶控件,也不是母版頁,那麼你就不需要使用FindControl方法。添加runat服務器標籤並使用該標識在代碼隱藏文件中訪問它。

apsx page: 

<div id="myDiv" runt="server" > 

// Your html 

</div> 

aspx.cs: 
private void ShowHideDiv(bool status) 
{ 
    myDiv.Visible = status; 
}