2017-01-05 74 views
1

Product.aspx “这个名字并不在当前的背景下存在”ASP.NET网站

<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1"> 
    <ItemTemplate> 
     <asp:textbox runat="server" ID="quantitytb"></asp:textbox> 
     <asp:Button CssClass="addtocart-button" runat="server" Text="Add to cart" ID="addtocartbutton" onclick="addtocartbutton_Click"></asp:Button> 

    </ItemTemplate> 
</asp:DataList> 

Product.aspx.cs

protected void addtocartbutton_Click(object sender, EventArgs e) 
{ 
    quantitytb.Text="1"; 
} 

Product.aspx

1号线
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Product.aspx.cs" Inherits="Product" %> 

以上是我的代码看起来像只是一小部分。我添加到我的Product.aspx页面的任何控件在.cs文件中都不起作用。将会出现一个错误,提示“名称'控件名'在当前上下文中不存在”。从字面上尝试了我可以在网上找到的所有解决方案,但无济于事。

请注意,我使用ASP.Net空白网站,而不是Web应用程序,所以没有designer.cs文件。

+0

包括在你的问题所需的行为会在这里 –

回答

2

你不能直接访问quantitytb因为它是一个DataList内。与任何数据绑定容器(gridview,repeater,formview等)类似,您必须将特定项目/行作为目标以查找其子控件。如果您的数据手中包含10个项目,这意味着您将有10次出现quantitytb - 如果您没有指定您定位的是哪个项目,则代码将引发错误。

如果你想修改这就是点击的按钮兄弟的文本框,也许你正在寻找的是这样的:

protected void addtocartbutton_Click(object sender, EventArgs e) 
{ 
    //Find the button that was clicked 
    Button addToCart = (Button)sender; 

    //Get the button's parent item, and within that item, look for a textbox called quantitytb 
    TextBox quantitytb = (TextBox)addToCart.Parent.FindControl("quantitytb"); 

    //Set that textbox's text to "1" 
    quantitytb.Text="1"; 
} 
+0

谢谢不错你这么多回复!但是,如果我的数据员有超过1个项目,我该如何使代码针对我想要的特定项目? – user7381027

+0

我现在的答案应该这样做。我们可以得到'sender'(被点击的按钮),然后得到它的父对象(数据列表项)。现在我们有了具体的项目,我们可以说“在那个特定的项目中,找到'quantitytb'并且改变它的文本。”我已经评论了我的代码,以使其更加清晰。 – Santi

+0

再次感谢你!有用!但是,如果我使用控件而不是文本框,则必须对c#代码进行哪些更改? '<输入RUNAT = “服务器” 类型= “号码” 的值= “1” 分钟= “0” 最大值= “99” 类= “qtyinput” ID = “qtyinput”>' – user7381027