Check value of checkboxes inside listview

I have a ListView with a check box inside that gets the identifier given dynamically.

I also have a button that when clicked should check if any of the checboxes is checked, but I'm not sure how to do it.

Any idea on how I can do this?

thank

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)
{
   ???????
}
+3
source share
1 answer

Disclaimer: I am more of a back-end / wpf developer. There are probably more elegant solutions, but it seems to work.

Change your flag identifier so that it is not unique (sorry, this will break the w3c check) and install it on the runat server and set the CheckBox value for your Id data source:

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

ListView 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;
    }
  }
}

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
}
+5

Source: https://habr.com/ru/post/1790316/


All Articles