title: C# gridview column order reset
body: <p>I am trying to dynamically reorder gridview columns based on the needs of a user for a web application. </p>
  
  <p>Say for example the default table starts with the columns A B C D ... W X Y Z.</p>
  
  <p>The user brings up another table but it must have the order C D E F... Y Z A B.</p>
  
  <p>The current implementation I have is the following:</p>
  
  <pre><code>       &lt;asp:GridView ID="lettertable" ClientIDMode="Static" runat="server" NullDisplayText="" AutoGenerateColumns="False"&gt;
  
            &lt;Columns&gt;
                 &lt;asp:BoundField DataField="A" ReadOnly="false" ItemStyle-CssClass="tlet ssA" /&gt;
                 &lt;asp:BoundField DataField="B" ReadOnly="false" ItemStyle-CssClass="tlet ssB" /&gt;
                 &lt;asp:BoundField DataField="C" ReadOnly="false" ItemStyle-CssClass="tlet ssC" /&gt;
                 &lt;asp:BoundField DataField="D" ReadOnly="false" ItemStyle-CssClass="tlet ssD" /&gt;
                 &lt;asp:BoundField DataField="E" ReadOnly="false" ItemStyle-CssClass="tlet ssE" /&gt;
            ...etc
            &lt;/Columns&gt;
        &lt;/asp:GridView&gt;
  </code></pre>
  
  <p>The codebehind involves a rather extensive set of conditionals (to account for startup vs nonstartup, vs same set of records vs across different) that look like the following:</p>
  
  <pre><code>         if (letchg == 0)
              {
                  for (int i = 1; i &lt; rep; i++)
                  {
                      var columnMove = grid.Columns[1];
                      grid.Columns.RemoveAt(1);
                      grid.Columns.Insert((26), columnMove);
                  }
              }
              if (letchg == 2)
              {
                  for (int i = 1; i &lt; rep; i++)
                  {
                      var columnMove = grid.Columns[1];
                      grid.Columns.RemoveAt(1);
                      grid.Columns.Insert((26), columnMove);
                  }
              }
              if (letchg == -2)
              {
                  for (int i = 1; i &lt; rep; i++)
                  {
                      var columnMove = grid.Columns[1];
                      grid.Columns.RemoveAt(1);
                      grid.Columns.Insert((26), columnMove);
                  }
              }
          }
  </code></pre>
  
  <p>There are different conditions for startup vs switching between tables, because once I reorder the columns from ABCD...WXYZ to CDEF...YZAB, it stays that way. So if I wanted to go to DEFG...ZABC, I move only one column, since it is relative. The BIG PROBLEM is that if the user hits the refresh button (creating a postback), it will resend the last operation, screwing up the whole order. </p>
  
  <p>Is it possible to just reset the column order of the table every time to ABCD...WXYZ before conducting the reordering? That way it is not a relative reordering? Or is there a better way to do this?</p>