我有一个 ListView,里面有一个复选框字段,可以动态设置 id。
我还有一个按钮,按下时需要检查是否已选中任何复选框,但我不确定如何完成此操作。
关于如何完成这项工作的任何想法?
谢谢
这是我的代码:
<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)
{
???????
}
最佳答案
免责声明:我更像是一名后端/wpf 开发人员。可能有更优雅的解决方案,但这似乎有效。
更改您的复选框 ID,使其不是唯一的(抱歉,这会破坏 w3c 验证)并将其设置为运行服务器并将 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>
然后您可以遍历 ListView 的项目集合并找到复选框:
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
}
关于c# - 检查 ListView 中复选框的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4914505/