I am using JQuery to sort my GridView. I want to save the GridView as excel. But excel does not contain the sorted order. How can I send the sorted order to the server?

This can be accomplished by having an additional TemplateField with a HiddenField. The HTML markup for Gridview will look like this:


<asp:GridView ID="gv" runat="server" DataSourceID="sql" 
AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField>
         <HeaderStyle CssClass="hidden" />
         <ItemStyle CssClass="hidden" />
          <ItemTemplate>
            <asp:HiddenField ID="hdn" runat="server" />
          </ItemTemplate>
        </asp:TemplateField> 
        <asp:BoundField DataField="au_lname" />                
    </Columns>
</asp:GridView>

The javascript for saving the sorted order into the HiddenField is shown below. It is getting all the hiddencontrols within each table cell and updating its value with the row index.


<script type="text/javascript"  >

    function setOrder() {
        var gv = document.getElementById('gv');
        for (var i = 1; i < gv.rows.length; i++) {
            var hdns = gv.rows[i].cells[0].getElementsByTagName('input');
            hdns[0].value = i;           
        }
    }
    
</script>
<style type="text/css">
 .hidden { display: none; }
</style>

In the server-side, the excel should be written in the same order as the row-index in the hidden fields. This can be done using code like this:


protected void btnSubmit_Click(object sender, EventArgs e)
{
    for (int i = 1; i <= gv.Rows.Count; i++)
    {
        GridViewRow gvr = GetSortedRow(i);
        Response.Write(gvr.Cells[1].Text);
    }
}

private GridViewRow GetSortedRow(int index)
{
    foreach (GridViewRow gvr in gv.Rows)
    {
        HiddenField hf = gvr.FindControl("hdn") as HiddenField;
        if (hf.Value == index.ToString())
            return gvr;
    }

    return null;
}