尝试在按钮上执行FindControl时,出现空引用异常。我有一个购物车设置,其中有一个基于母版页的内容页(.aspx)。在内容页面上,有一个占位符控件,我在其中动态添加用户控件(每个产品一个控件,每个控件中都有一个“添加到购物车”按钮)。
当用户单击按钮将商品添加到购物车时,我可以将其成功添加到购物车中,然后计算购物车中的商品数量,如果数量超过1,则尝试显示“结帐”按钮,或者如果购物车中没有,则将其隐藏。
我正在使用FindControl,但收到空引用错误。为什么找不到结帐按钮?我当前的代码如下:
主页面(模板主版):
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="template.master.cs" Inherits="OUWP.template" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head runat="server"></head>
<body>
<form id="form1" runat="server">
<asp:ContentPlaceHolder ID="m_cph_body" runat="server"></asp:ContentPlaceHolder>
</form>
</body>
</html>
内容页(shop.aspx)
<%@ Page Title="" Language="C#" MasterPageFile="~/template.Master" AutoEventWireup="true" CodeBehind="shop.aspx.cs" Inherits="OUWP.shop" %>
<%@ MasterType VirtualPath="~/template.Master" %>
<asp:Content ID="Content2" ContentPlaceHolderID="m_cph_body" runat="server">
<asp:PlaceHolder ID="Catalogue" runat="server">
<!-- this is where the user controls are dynamically generated-->
</asp:PlaceHolder>
<asp:Panel ID="pnl_Basket" runat="server">
<div>
<asp:LinkButton ID="lbtnCheckout" runat="server">Continue to Checkout</asp:LinkButton>
</div>
</asp:Panel>
</asp:Content>
用户控制页(PurchasableProduct.ascx)
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PurchasableProduct.ascx.cs" Inherits="OUWP.CustomControls.PurchasableProduct" %>
<asp:UpdatePanel ID="udpBody" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlPurchasableProduct" runat="server">
<asp:LinkButton ID="lbtnAddLine" runat="server" OnClick="lbtnAddLine_Click"></asp:LinkButton>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="lbtnAddLine" />
</Triggers>
</asp:UpdatePanel>
隐藏用户控制代码(PurchasableProduct.ascx.cs)
protected void lbtnAddLine_Click(object sender, EventArgs e)
{
// try to find checkout button on parent page of control
System.Web.UI.Page page = (System.Web.UI.Page)this.Page;
LinkButton Target1 = (LinkButton)page.FindControl("lbtnCheckout");
// count the items in the cart (saved in session variable)
DataTable dt = (DataTable)Session["varDataTableCart"];
Int32 ItemCount = 0;
Int Line Quantity = 0;
foreach (DataRow dr in dt.Rows)
{
Int32 LineQuantity = Convert.ToInt32(dt.Rows[dt.Rows.IndexOf(dr)]["Quantity"].ToString());
ItemCount = ItemCount + LineQuantity;
}
// if 1 or more items in cart, try to make button visible
if (ItemCount > 0)
{
Target1.Visible = true;
}
// otherwise no items in cart, so try to hide checkout button
else
{
Target1.Visible = false;
}
}
我还尝试使用下面的代码通过母版页进行操作,但这也不起作用:
MasterPage mp1 = (MasterPage)page.Master;
LinkButton Target1 = (LinkButton)mp1.Page.FindControl("lbtnCheckout");
答案 0 :(得分:0)
好的,所以我很幸运地尝试了这段代码,它起作用了,找到了我的按钮。使用当前控件的“父级”。
LinkButton Target1 =(LinkButton)this.Parent.FindControl(“ lbtnCheckout”);