我有网格视图,其中包含用于选择项目的复选框
如何过滤网格视图而不会丢失已检查的项目。
的GridView
<asp:GridView ID="gridpur" CssClass="table table-bordered text-nowrap" runat="server" AutoGenerateColumns="False" DataKeyNames="Pro_ID" >
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
过滤代码
StoreClass s = new StoreClass();
gridpur.DataSource = s.SearchPurchase(hdnSearchParam.Value, txtsearch.Text);
gridpur.DataBind();
Gridview数据源
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
StoreClass s = new StoreClass();
gridpur.DataSource = s.getpurchase();
gridpur.DataBind();
}
}
答案 0 :(得分:3)
您必须在Pro_ID
之前存储所选的复选框(似乎是DataBind
列/属性的键),然后再选择它们:
在你的过滤方法中:
List<string> selectedProIDs = gridpur.Rows.Cast<GridViewRow>()
.Select(row => new {
CheckBox = (CheckBox)row.FindControl("chkSel"),
ProID = gridpur.DataKeys[row.RowIndex].Value.ToString()
})
.Where(x => x.CheckBox.Checked)
.Select(x => x.ProID)
.ToList();
StoreClass s = new StoreClass();
gridpur.DataSource = s.SearchPurchase(hdnSearchParam.Value, txtsearch.Text);
gridpur.DataBind();
foreach(GridViewRow row in gridpur.Rows)
{
var checkBox = (CheckBox)row.FindControl("chkSel");
string proID = gridpur.DataKeys[row.RowIndex].Value.ToString();
checkBox.Checked = selectedProIDs.Contains(proID);
}