재우니의 블로그

Imagine you have a list of some items and checkboxes next to each item providing the ability for a user to make multiple choices and submit a result in one go. Weather you are implementing a news groups subscription, user survey or online products catalogue - the code behind is the same: we bind some object list to a data control like Repeater, add a checkbox to every item, set checkbox value to item ID.

Here is an example with list of books available for order

Repeater with checkboxes
<table>
    <asp:Repeater ID="rptBooks" runat="server"> 
        <ItemTemplate>
            <tr>     
                <td><input type="checkbox" runat="server" value='<%# Eval("BookID")%>' ID="chkBox" /></td>
                <td><%# Eval("Title")%></td>
                <td><%# Eval("Author")%> </td>
            </tr>
        </ItemTemplate>  
    </asp:Repeater>
</table>
<asp:Button ID="btnOrder" OnClick="btnOrder_Click" runat="server" Text="Order" />

When “Order” button is clicked we need get all selected book IDs (we store them in a value field of each checkbox). I suggest that we create an extension method that will do all the work and when we need to get selected items in any repeater in our code we will have to call only one method GetSelectedItems

repeater 의 checkbox 선택한 값을 추출하는 확장 메소드를 구현하자

public static class RepeaterExt
{
    /// <summary>
    /// Returns selected items array list in a repeater rpt
    /// </summary>
    /// <param name="chkBoxId">ID of a checkbox used in repeater to store the value of each item</param>
    public static ArrayList GetSelectedItems(this Repeater rpt, string chkBoxId)
    {
        var selectedValues = new ArrayList();
        for (int i = 0; i < rpt.Items.Count; i++)
        {
            var chkBox = rpt.Items[i].FindControl(chkBoxId) as HtmlInputCheckBox;
 
            if (chkBox != null && chkBox.Checked)
                selectedValues.Add(chkBox.Value);
        }
        return selectedValues;
    }
}

Now if we go back to our page with books catalog we can right the following:

배열 ArrayList 로 받아온다.

protected void btnOrder_Click(object sender, EventArgs e)
{
using extenstion method to get checked items
selectedValues array will contain BookIDs that were ordered and you can store them in the database or process as required by your code.

Note that this example assumes that you need to use <input runat=”server”…  to be able to pre-polulate checked values or keep the state of the checkboxes after the postback. If none of this functionality is needed, the simplest way to get selected values is to use standard html

선택한 값을 얻기 위해서  value 태그에 값을 할당한다.

<input type="checkbox" value='<%# Eval("BookID")%>' name="chkBox" />

When the “Order” button is clicked Request["chkBox"] will return comma delimited list of selected BookIDs.




원문 : http://www.objectreference.net/post/Get-Checked-Repeater-Items-Extension-Method.aspx