?
Solved

ASP.Net/C# - Sorting GridView code working how do I keep checkboxes checked?

Posted on 2009-03-31
3
Medium Priority
?
2,047 Views
Last Modified: 2012-05-06
Hello all I have all my gridviews sorting perfectly, however what happens is when I click on the sorting I lose all my checked checkboxes in my grid.  Any idea how I can keep them checked?  Here is what I have below as an example:


protected void EDIAccountData_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataSet dsAccountData = (DataSet)Session["dsAccountData"];
            DataTable dtAccountData = dsAccountData.Tables[0];
 
            if (dtAccountData != null)
            {
                DataView dataView = new DataView(dtAccountData);
                dataView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
 
                EDIAccountData.DataSource = dataView;
                EDIAccountData.DataBind();
            }
        }
 
 private string GetSortDirection(string column)
        {
 
            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";
 
            // Retrieve the last column that was sorted.
            string sortExpression = Session["SortExpression"] as string;
 
            if (sortExpression != null)
            {
                // Check if the same column is being sorted.
                // Otherwise, the default value can be returned.
                if (sortExpression == column)
                {
                    string lastDirection = Session["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }
 
            // Save new values in ViewState.
            Session["SortDirection"] = sortDirection;
            Session["SortExpression"] = column;
 
            return sortDirection;
        }
 
ASPX PAGE:
 <asp:GridView ID="EDIAccountData" Width="650px" runat="server" CellPadding="4"
                ForeColor="#333333" Font-Size="Small" GridLines="None" AllowSorting="true" AllowPaging="false"  
                OnSorting="EDIAccountData_Sorting" AutoGenerateColumns="False" DataKeyNames="CUS_Parent">
                <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
                <RowStyle BackColor="#76B0F0" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
                <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
                <HeaderStyle VerticalAlign="Bottom" HorizontalAlign="Left" BackColor="#3D6592" Font-Bold="True" ForeColor="White" />
                <AlternatingRowStyle BackColor="White" />
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:CheckBox runat="server" ID="AcctCheckBox" AutoPostBack="true" OnCheckedChanged="AcctCheckBox_CheckedChanged" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="CUS_Parent" HeaderStyle-Width="125px" ItemStyle-Width="125px" HeaderText="Parent Account" SortExpression="CUS_Parent" />
                    <asp:BoundField DataField="Parent_Name" HeaderStyle-Width="250px" ItemStyle-Width="250px" HeaderText="Customer Name" SortExpression="Parent_Name" />
                    <asp:BoundField DataField="Billrun" HeaderStyle-Width="75px" ItemStyle-Width="75px" HeaderText="Billrun" SortExpression="Billrun" />
                    <asp:BoundField DataField="folder" HeaderStyle-Width="100px" ItemStyle-Width="100px" HeaderText="Vendor" SortExpression="folder" />
                    <asp:BoundField DataField="Map_Version" HeaderStyle-Width="100px" ItemStyle-Width="100px" HeaderText="Map Version" SortExpression="Map_Version" />
                </Columns>
            </asp:GridView>

Open in new window

0
Comment
Question by:sbornstein2
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 3

Accepted Solution

by:
JenniQ earned 2000 total points
ID: 24033380
What you need to do is subscribe to a GridView event. Create a delegate event handler that will look at all the checked fields and then assign their "checked" value to... well... "checked"  =P

GridView Events

Sorting:: Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation

RowCreated: Occurs when a row is created in a GridView control.

RowDataBound: Occurs when a data row is bound to data in a GridView control.

Here are three options that might work for ya.

And here is the code sample that you could edit to fufill you every desire:

Occurs when a data row is bound to data in a GridView control (of course you'll have to edit it to look at the isChecked property and do the assignment)

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
  {

    //Retrieve the table from the session object.
    DataTable dt = Session["TaskTable"] as DataTable;

    if (dt != null)
    {

      //Sort the data.
      dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
      TaskGridView.DataSource = Session["TaskTable"];
      TaskGridView.DataBind();
    }

  }

  private string GetSortDirection(string column)
  {

    // By default, set the sort direction to ascending.
    string sortDirection = "ASC";

    // Retrieve the last column that was sorted.
    string sortExpression = ViewState["SortExpression"] as string;

    if (sortExpression != null)
    {
      // Check if the same column is being sorted.
      // Otherwise, the default value can be returned.
      if (sortExpression == column)
      {
        string lastDirection = ViewState["SortDirection"] as string;
        if ((lastDirection != null) && (lastDirection == "ASC"))
        {
          sortDirection = "DESC";
        }
      }
    }

    // Save new values in ViewState.
    ViewState["SortDirection"] = sortDirection;
    ViewState["SortExpression"] = column;

    return sortDirection;
  }

  protected void Page_Load(object sender, EventArgs e)
  {

    if (!Page.IsPostBack)
    {

      // Create a new table.
      DataTable taskTable = new DataTable("TaskList");

      // Create the columns.
      taskTable.Columns.Add("Id", typeof(int));
      taskTable.Columns.Add("Description", typeof(string));

      //Add data to the new table.
      for (int i = 0; i < 10; i++)
      {
        DataRow tableRow = taskTable.NewRow();
        tableRow["Id"] = i;
        tableRow["Description"] = "Task " + (10 - i).ToString();
        taskTable.Rows.Add(tableRow);
      }

      //Persist the table in the Session object.
      Session["TaskTable"] = taskTable;

      //Bind the GridView control to the data source.
      TaskGridView.DataSource = Session["TaskTable"];
      TaskGridView.DataBind();

    }

  }

</script>

<html >
<head runat="server">
    <title>Sorting example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

      <asp:GridView ID="TaskGridView" runat="server"
        AllowSorting="true"
        OnSorting="TaskGridView_Sorting" >
      </asp:GridView>

    </div>
    </form>
</body>
</html>


Hope this helps!!

-- jq
0
 

Author Closing Comment

by:sbornstein2
ID: 31565040
thanks so much for the great response and example.
0
 
LVL 3

Expert Comment

by:JenniQ
ID: 24051717
I'm glad I could have been of service! Good luck in the future.

-- jq
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
Suggested Courses

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question