check value of checkboxes inside listview

10,138

disclaimer: I'm more of a back-end/wpf developer. There are likely more elegant solutions, but this seems to work.

Change your checkbox id so it is not unique (sorry, this will break w3c validation) and set it to runat server and set the value of the CheckBox to your data source's Id:

<ItemTemplate>
<tr>
  <td class="firstcol">
    <label runat="server"><%# Eval( "Id" ) %></label>
    <input id="MyCheckBox" value='<%# Eval("Id") %>'
           type="checkbox" runat="server" />
  </td>
</tr>
</ItemTemplate>

You can then iterate through the ListView's items collection and find the CheckBoxes:

protected void btnDownload_Click( object sender, EventArgs e )
{
  foreach( ListViewDataItem item in ListView1.Items )
  {
    var chk = item.FindControl( "MyCheckBox" ) as System.Web.UI.HtmlControls.HtmlInputCheckBox;
    if( chk != null && chk.Checked )
    {
      string value = chk.Value;
    }
  }
}

If you wanted a bit of Linq:

protected void btnDownload_Click( object sender, EventArgs e )
{
    var checkedCheckBoxes = ListView1.Items.Select( x => x.FindControl( "MyCheckBox" ) as HtmlInputCheckBox )
    .Where( x => x != null && x.Checked );

    // do stuff with checkedCheckBoxes
}
Share:
10,138
user441365
Author by

user441365

Updated on July 16, 2022

Comments

  • user441365
    user441365 almost 2 years

    I have a ListView with a checkbox field inside that gets the id set dynamically.

    I also have a button that when pressed needs to check if any of the checboxes have been checked but I'm not sure how to get this done.

    Any idea on how I can get this done?

    Thanks

    This is my code:

    <asp:ListView ID="ListView1" runat="server" DataKeyNames="Id"  
        DataSourceID="EntityDataSource1" EnableModelValidation="True"> 
    
        <ItemTemplate>
            <tr>
                <td class="firstcol">
                    <input id='Checkbox<%# Eval("Id") %>' type="checkbox" />
                </td>
            </tr>
        </ItemTemplate>
    
        <LayoutTemplate>
           <table width="100%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                    <th width="50" scope="col" class="firstcol">
    
                    </th>
                </tr>
                <tr ID="itemPlaceholder" runat="server"></tr>
            </table>
            <asp:Button ID="btnDownload" runat="server" Text="Download" Height="26px" 
        onclick="btnDownload_Click" />
        </LayoutTemplate>
    </asp:ListView>
    
    
    
    protected void btnDownload_Click(object sender, EventArgs e)
    {
       ???????
    }