开发者

check value of checkboxes inside listview

开发者 https://www.devze.com 2023-02-09 02:00 出处:网络
I have a ListView with a checkbox field inside 开发者_运维技巧that gets the id set dynamically.

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)
{
   ???????
}


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消