C# ASP.NET网站;该名称在当前上下文中不存在;
Product.aspxC# ASP.NET网站;该名称在当前上下文中不存在;,c#,asp.net,C#,Asp.net,Product.aspx <asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1"> <ItemTemplate> <asp:textbox runat="server" ID="quantitytb"></asp:textbox> <asp:Button CssClass="addtocart-button" runat=
<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>
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Product.aspx.cs" Inherits="Product" %>
Product.aspx的第1行
<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>
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Product.aspx.cs" Inherits="Product" %>
以上只是我的代码的一小部分。添加到Product.aspx页面的任何控件在.cs文件中都不起作用。将出现一个错误,提示“当前上下文中不存在名称“control name”。我尝试了所有我能在网上找到的解决方案,但都无济于事
请注意,我使用的是ASP.Net空网站,而不是Web应用程序,因此没有designer.cs文件。您无法直接访问
quantitytb
,因为它位于数据列表中。与任何数据绑定容器类似(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";
}
非常感谢您的回复!但是,如果我的数据列表有多个项,我如何使代码针对我想要的特定项?我当前的答案应该这样做。我们可以获取发送者(单击的按钮),然后获取其父项(数据列表项)。现在我们有了特定的项目,我们可以说“在该特定项目中,查找quantitytb
并更改其文本。”我已经对我的代码进行了注释,以使其更加清晰。再次感谢您!它起作用了!但是,如果我要使用控件而不是文本框,我需要对c代码做什么更改
实际上,如果这是您使用输入的唯一原因,您可以将type=“number”
放在
上。在您的问题中包含所需的行为会很好