'Accessing control inside datalist
my name is Prince. I have a datalist named datalist1, i inputed a label, image and button in the datalist. I inputed the image of a field from my database in my image tag and the id of the same field in my label tag. I'm trying to implement ecommerce functionality, so when i click the button it'll redirect me to my product page AND input the id(from the label tag) in the url path.
ive tried:
protected void img_Click(object sender, EventArgs e)
{
DataListItem dli = this.DataList1.Controls[this.DataList1.Controls.Count - 1] as DataListItem;
Label lbl = dli.FindControl("itemiD") as Label;
Response.Redirect("product.aspx?id="+lbl.Text+"");
}
The above code worked, but it only game me the id of the last item in my datalist1.
Then i tried the following below
protected void img_Click(object sender, EventArgs e)
{
foreach (DataListItem item in DataList1.Items)
{
Label lbl = (Label)item.FindControl("itemiD");
Response.Redirect("product.aspx?id=" + lbl.Text + "");
}
}
The following worked as well, but only gave me the id of the first item in my datalist1. Please how do i get the id of the clicked item in the datalist to the url.
P.S img_Click() is the event to handle the code :)
Here is the front end
<asp:DataList ID="DataList1" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" Width="100%" BorderColor="#336699" BorderStyle="None" BorderWidth="2px" OnSelectedIndexChanged="DataList1_SelectedIndexChanged">
<ItemTemplate>
<div style="height:auto;" class="dimage">
<asp:Label runat="server" Text='<%#Eval("Name") %>' Font-Bold="true" Font-Size="10pt" ForeColor="#336699" Width="100%"/>
<br />
<img id="Image2" runat="server" src='<%#"GetImage.aspx?id="+Eval("id") %>' style="width:auto; height:150px;" class="d_image" onclick="img_Click" /> <br />
<asp:Label runat="server" Text='<%#Eval("id") %>' ID="itemiD" />
<br />
<asp:Button ID="Button1" runat="server" OnClick="img_Click" Text="Buy Now" /><br /><br />
</div>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Top" />
</asp:DataList>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
