名称' Label2.Text'在当前上下文中不存在 Catalog.aspx
<asp:DataList ID="DataList1" runat="server" DataKeyField="Id" DataSourceID="SqlDataSource1" RepeatColumns="4" RepeatLayout="Flow">
<ItemTemplate>
<div class="Item">
<div class="name">
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
</div>
<div>
Код:<asp:Label ID="Label2" runat="server" Text='<%# Eval("Id") %>' />
</div>
<img src="<%# Eval("Image") %>" height="115" alt="item"/>
<div class="price">
Цена:
<asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("Price")%>' />p.
<asp:Button ID="Button2" runat="server" ForeColor="Black"
onclick="Button2_Click" Text="В КОРЗИНУ" />
</div>
<div class="desc">
<asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>' />
</div>
</div>
</ItemTemplate>
</asp:DataList>
Catalog.aspx.cs
sqlCon.Open();
SqlCommand cmd_SQL = new SqlCommand("INSERT INTO Cart(ClientId,ProductId,Amount) VALUES (@ClientId,@ProductId,@Amount)", sqlCon);
cmd_SQL.Parameters.Add("@ClientId", SqlDbType.NVarChar).Value =Membership.GetUser().ProviderUserKey.ToString();
cmd_SQL.Parameters.Add("@ProductId", SqlDbType.NVarChar).Value =Label2.Text;
cmd_SQL.Parameters.Add("@Amount", SqlDbType.NVarChar).Value = 1;
cmd_SQL.CommandType = CommandType.Text;
cmd_SQL.ExecuteNonQuery();
名称&#39; Label2.Text&#39;在当前上下文中不存在
答案 0 :(得分:2)
您的标签位于商品模板内,这意味着您无法只访问页面上任何旧位置。如果要获取对标签内部值的访问权限,则需要绑定其中一个DataList事件,例如OnItemCommand(例如,如果您希望通过单击命令按钮来访问该值)。您可以在事件处理程序内部使用FindControl来访问该值。例如:
<asp:DataList runat="server" ID="test" OnItemCommand="test_ItemCommand">
<ItemTemplate>
<asp:Label runat="server" ID="Label2" Text="Test" />
</ItemTemplate>
</asp:DataList>
protected void test_ItemCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e)
{
if (e.Item != null)
{
var label2 = e.Item.FindControl("Label2");
if (label2 != null && label2 is Label)
{
var productID = ((Label)label2).Text;
// now you have the contents of the label's text property
}
}
}