2017-01-05 73 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