Search code examples
c#asp.netrepeater

How to pass the id when a checkbox is checked in asp repeater?


I have an asp repeater that binds the list of orders by tracking number. I want to know how could I pass the id of the selected row when a checkbox is checked. I did this to bind the checked checkbox only.

Repeater

<asp:Repeater ID="Repeater2" runat="server" OnItemDataBound="Repeater2_ItemDataBound">
    <HeaderTemplate>
        <table class=" table table-bordered">
            <tr>
                <th></th>
                <th>Order Type</th>
                <th>Job Name</th>
                <th>Price</th>
            </tr>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td>
                <asp:CheckBox ID="chkDisplayTitle" runat="server" /></td>
            <td><%#Eval("Order") %></td>
            <td><%#Eval("Job_Name") %></td>
            <td><%#Eval("Price") %></td>
        </tr>

    </ItemTemplate>
    <FooterTemplate>
        <td></td>
        <td></td>
        <td>
            <td>Subtotal:
        <asp:Label ID="lblSubtotal" runat="server"></asp:Label>
            </td>
        </td>
        </tr>
        </table>
    </FooterTemplate>
</asp:Repeater>

Code Behind

private void ConsolidateItems()
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);

    //======= Parameterized select Query.
    string cmdText = "SELECT * FROM Order_TB WHERE Tracking_Number=@tracking AND Status=@status";

    //====== Providning information to SQL command object about which query to 
    //====== execute and from where to get database connection information.
    SqlCommand cmd = new SqlCommand(cmdText, con);

    //===== Adding parameters/Values.
    cmd.Parameters.AddWithValue("@tracking", hfid.Value);
    cmd.Parameters.AddWithValue("@status", "Accepted");


    if (con.State == ConnectionState.Closed)
    {
        con.Open();
    }

    Repeater2.DataSource = cmd.ExecuteReader();
    Repeater2.DataBind();
    con.Close();
}

Solution

  • On ASPX :

      <asp:CheckBox ID="chkBoxID" runat="server" OnCommand="doSomething_Checked" 
       CommandArgument="<%# Some Binding Information%>" CommandName="NameForArgument"> </asp:CheckBox>
    

    On Code-Behind :

     protected void doSomething_Checked(object sender, CommandEventArgs e)
       {
    
                CheckBox ctrl = (CheckBox)sender;
                RepeaterItem rpItem = ctrl.NamingContainer as RepeaterItem;
                if (rpItem != null)
                {
                    CheckBox chkBox = (CheckBox)rpItem.FindControl("chkBoxID");
                    chkBox.DoSomethingHere...
                }
       }
    

    You Can Do it Like this way ....