检查listview中复选框的值

use*_*365 3 .net c# asp.net listview

我有一个带有复选框字段的Lis​​tView,它可以动态获取id.

我还有一个按钮,当按下时需要检查是否有任何checbox已被检查,但我不知道如何完成.

关于如何完成这项任务的任何想法?

谢谢

这是我的代码:

<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)
{
   ???????
}
Run Code Online (Sandbox Code Playgroud)

Met*_*urf 5

免责声明:我更像是一个后端/ wpf开发人员.可能有更优雅的解决方案,但这似乎有效.

更改您的复选框ID,使其不是唯一的(抱歉,这将破坏w3c验证)并将其设置为runat服务器并将CheckBox的值设置为您的数据源的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>
Run Code Online (Sandbox Code Playgroud)

然后,您可以遍历ListView的items集合并找到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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果你想要一点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
}
Run Code Online (Sandbox Code Playgroud)