过滤后,选定的行将被取消选中

时间:2016-04-26 15:03:24

标签: c# asp.net gridview

我有网格视图,其中包含用于选择项目的复选框

如何过滤网格视图而不会丢失已检查的项目。

的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();
    }
}

1 个答案:

答案 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);
}