Search code examples
gridviewauto-generateautogeneratecolumn

Change Order of columns


I am using gridView. I have 4 auto generated columns and 1 generated by my self. Now the column which i have generated is displayed first and then the auto generated columns. I want to display auto generated columns first then my generated column.


Solution

  • for that you need to know the datafield (data item that you want to bound) and use either template or boundcolumns to accomplish that, like:

    an auto generate column grid

    <asp:GridView id="gv" runat="server" AutoGenerateColumns="True">
    </asp:GridView>
    

    a manually generate column grid

    <asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField HeaderText="My First Column" DataField="myField1" />
            <asp:BoundField HeaderText="My Second Column" DataField="myField2" />
            <asp:BoundField HeaderText="My Third Column" DataField="myField3" />
    
            <asp:TemplateField HeaderText="My Fourth Column">
                <ItemTemplate>
                    <asp:Label ID="lbl" runat="server" Text='<%# Eval("myField4") %>' />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    

    You can use either a BoundField or a TemplateField, with the template you can do much more, create a dropdown instead of a Label, etc... in a BoundField the output will always be a Label and you can only format the string value using the .NET nomenclature like {0:d}

    You have more pre-defined templates to use such as Checkbox, Button, Hyperlink, Command and Image.