The name ' ' does not exist in the current context

The name 'Label2.Text' does not exist in the current context Catalog.aspx

 <asp:DataList ID="DataList1" runat="server" DataKeyField="Id" DataSourceID="SqlDataSource1" RepeatColumns="4" RepeatLayout="Flow">
        <div class="Item">
            <div class="name">
                <asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
                Код:<asp:Label ID="Label2" runat="server" Text='<%# Eval("Id") %>' />
            <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 class="desc">
                <asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>' />



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;

The name 'Label2.Text' does not exist in the current context


Your label is inside of an item template, which means you cannot just access it any old place on the page. If you want to gain access to the value inside the label, then you need to tie into one of the DataList events, such as OnItemCommand (if you wanted to access the value as the result of a command button click, for instance). You can use FindControl inside of the event handler to access the value. For example:

<asp:DataList runat="server" ID="test" OnItemCommand="test_ItemCommand">
        <asp:Label runat="server" ID="Label2" Text="Test" />

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

Need Your Help

Is the following enum validator thread safe?

java generics enums bean-validation

I have implemented an enum validator following the older posts here. I was wondering whether this following code is thread safe or not? I have got many different enums for which I need to use this

Is there an easy way to generate ordered couples in Ruby

ruby arrays foreach range each

I was wondering if there is something similar to the Range but not with integers but with ordered couples (x, y). I am wondering if there is an easy way to do something like this: