Search code examples
asp.netsql-server-2012datatablesasprepeater

how to understand which rows selected in repeater?


I have a slideshow that images load from sql server.
here is my html code:

                <!-- Elastislide Carousel -->
                <ul id="Ul1" class="elastislide-list">
                    <asp:Repeater ID="Repeater2" runat="server">
                        <ItemTemplate>
                    <li>

                         <asp:Label ID="lbl" runat="server" Text='<%#Eval("IDMusic") %>' Visible="True"></asp:Label>
                            <asp:ImageButton ID="ImageButton1" runat="server"  ImageUrl='<%#Eval("ImageUrl") %>' Width="250px" Height="250px" OnClick="ImageButton1_Click" />&nbsp;&nbsp;

                    </li>
                        </ItemTemplate>
                     </asp:Repeater>
                </ul>
                <!-- End Elastislide Carousel -->
            <br /><br />

        </div>
    </div>    

Now when, I run Project and user click on one of the imageButtons, I want to understand what is he/she clicked? for example he/she click on second ImageButton, Then I want to save IDMusic into a session and use this session in another page but I don't know how can i get IDmusic user clicked on?
here is my code behind :

    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
 {
     foreach (RepeaterItem item in Repeater2.Items)
     {

         Label lbl = (Label)item.FindControl("lbl");
         if (lbl != null)
         {
             Session["selectedmusicID"] = lbl.Text;
         }
     }

     Response.Redirect("music.aspx");

 }

Solution

  • There is no easy way to do so while handling click on the image itself. However you can leverage ItemCommand event here, which is a repeater event. Basically when some control is clicked inside the repeater, it generates a command in repeater which you can handle, and you can have item-specific arguments for it.

    To define a command and args:

    <asp:ImageButton ID="ImageButton1" ... CommandName="Select" CommandArgument='<%#Eval("IDMusic") %>' />
    

    Command name here is custom, choose whatever you like. Now subscribe to the event of the repeater:

    <asp:Repeater ID="Repeater2" runat="server"
        OnItemCommand="Repeater2_ItemCommand">
    

    And to handle:

    protected void Repeater2_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "Select") //just in case you have more than one
        {
            e.CommandArgument //here is your ID
        }
    }