C #: reordering columns when binding DataTable to GridView

How can I change the display order of columns from a DataTable?

For example, dataTable "dt" contains two columns "a" and "b". I bind it to the GridView as follows:

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

But I would like the GridView to first display "b" (on the left).

The important point: I use this to export to Excel, and there is no actual output to the screen using:

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

Thanks!

+4
source share
2 answers

Yes, you can do it in front. Something like that:

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

EDIT:

You are not talking about the front? This is cool - I like the call:

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

(It's great to assume that C # 3 these days isn't it?)

+5
source

This often occurs in interviews. You upload the contents of the table to an excel file, which is good, and you use html in xl, which is great. BUT - you take the contents of the database table and put it in memory (DataTable). Overtime work as this data grows allows you to use more and more memory on the server, especially if there are parallel requests for this report.

To fix: use DataReader instead and manually populate the GridView (this solves the problem you wrote about) - or better yet, use something like Simple OOXML and write the data directly to the XML representation of the .xlsx table.

+1
source

Source: https://habr.com/ru/post/1305657/


All Articles