Phantomazi
Phantomazi

Reputation: 408

Is it possible to access element from inside DataList

I am working on a car adverts website. Currently I am trying to do a simple wish list feature allowing the user to store certain cars to his wish list on button click. My cars are presented to the user via DataList. As there is only one button which is repeatedly created on every item from the list I wanted on click to check which record from the DB corresponds to the item where the button was clicked and then add it to another wish list DB.

So far I have come up with this:

<ItemTemplate>
    carID:
    <asp:Label ID="carIDLabel" runat="server" Visible="false" 
         Text='<%# Eval("carID") %>' />
    <br />                
    <asp:Button ID="btn_wishList" runat="server" Text="Add to Wishlist" 
    onclick="btn_wishList_Click" />
    <br />
</ItemTemplate> 

And the button code:

//table adapters initialization ommited


foreach (DataRow row in carDetailsTable.Rows) 
if (carIDLabel.Text == System.Convert.ToString(row["carID"]))
{
    //DB insertion ommited
}

The problem I am encountering is that on the button code it says:

The name 'carIDLabel' does not exist in the current context.

Any suggestions how to access the Label's information or any other smarter ways to compare and then add to the wishDB ?

Upvotes: 1

Views: 497

Answers (1)

Daryl Young
Daryl Young

Reputation: 394

You can put the ID directly in the Button control as a command argument and handle the OnCommand event:

<asp:Button ID="btn_wishList" runat="server" Text="Add to Wishlist" CommandArgument="<%# Eval("carID") %>" OnCommand="btn_wishList_Command" />

Your event handler would be something like:

   protected void btn_wishList_Command(object sender, CommandEventArgs e)
   {
      string id = (string)e.CommandArgument;
   }

Upvotes: 1

Related Questions