So I have this checkbox inside a gridview, and it is working properly for the most part. However, I am trying to implement column-sorting to the grid, and it is causing an issue with the checkbox. When I do my initial fetch from the database, it populates the checkboxes properly, but when I click on a column to sort by it, all of my checkboxes get cleared out.
It seems that this is a problem with the Databind being done by the gridview, but I’m not sure what I’m doing wrong. My research into the issue makes me feel like I have it right, but I don’t know for sure (legacy code: I hate it).
<asp:GridView ID="UserListGrid" runat="server"
OnSorting="UserListGrid_Sort" AllowSorting = "True" AutoGenerateColumns="False"
AllowPaging="True" PageSize="25" OnRowDataBound="UserListGrid_RowDataBound"
OnPageIndexChanging="UserListGrid_PageIndexChanging">
.
.
.
<ItemTemplate>
<asp:CheckBox ID="ActiveCheck" runat="server" SortExpression="ActiveCheck"/>
</ItemTemplate>
.
.
.
protected void UserListGrid_Sort(object sender, GridViewSortEventArgs e)
{
// ViewState["CurTab"] = 0;
DataTable Data = myData.GetSessionRoster(TeamID);
DataView UserListView = new DataView(Data);
ViewState["SortDirection"] = myData.ConvertSortDirectionToSql(ViewState["SortDirection"] == null ? "" : ViewState["SortDirection"].ToString());
UserListView.Sort = e.SortExpression + " " + ViewState["SortDirection"];
UserListGrid.DataSource = UserListView;
UserListGrid.DataBind();
}
Is there anything obviously wrong with my sorting? I can provide more code if needed.
As requested, here is UserListGrid_RowDataBound
protected void UserListGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
{
return;
}
// See which users are active
CheckBox ActiveCheck = (CheckBox)e.Row.Cells[1].FindControl("ActiveCheck");
if (ActiveCheck != null)
{
ActiveCheck.Enabled = true;
if (e.Row.Cells[11].Text.Equals("1") && !Page.IsPostBack)
{
ActiveCheck.Checked = true;
ActiveCheck.DataBind();
}
}
}
It looks like you’re populating checkboxes not from the data base, but corresponding to the contents of your cell 11 (whatever it is).
I appeal to this code line:
While sorting you rebind your gridview, but you restrict populating and rebinding of your checkboxes on postback. This could be a reason for checkboxes loosing values.