C#: Changing the order of columns when binding DataTable to a GridView

How is it possible to change the displayed order of columns from a DataTable?

For example, dataTable “dt” contains two columns “a” and “b”. I bind it to a GridView like this:

gridView.DataSource = dt;
gridView.DataBind();

But I’d like the GridView to display “b” first (leftmost).

Important point: I’m using this to export to Excel and there’s no actual output to screen, using:

 HtmlTextWriter htw = new HtmlTextWriter(sw);
 gridView.RenderControl(htw);

Thanks!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

yes you can do it in the front end. Something along these lines:

<asp:GridView runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="b" />
        <asp:BoundField DataField="a" />
    </Columns>
</asp:GridView>

EDIT:

No front end you say? That’s cool – I like a challenge:

            gridView.AutoGenerateColumns = false;
        gridView.Columns.Add(new BoundField { DataField = "b" });
        gridView.Columns.Add(new BoundField { DataField = "a" });

(It’s cool to assume C#3 these days isn’t it?)

Method 2

This comes up in an interview question quite often. You are dumping the contents of a table to an excel file which is fine, and you are using html in xl which is fine. BUT – you are taking the contents of the database table and placing it into memory (DataTable). Overtime as this data grows it could use more and more memory on the server, especially if there are concurrent requests for this report!!

Fix: Use a DataReader instead and manually populate the GridView (this solves the problem you posted about) — or better still use something like Simple OOXML and write the data directly to a xml representation of an .xlsx spreadsheet.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x