I have a grid view and I add columns to it by code:
//Retrieve "Table" from database gridOffers.DataSource = table; gridOffers.DataBind();
The columns added by code are being added AFTER the button, which is not what I need:

How do I make sure the Add To Cart button the very last thing?
Source of gridView:
<Columns>
<asp:ImageField DataImageUrlField="ImageUrl" ControlStyle-Width="100"
ControlStyle-Height = "100" HeaderText = "Preview Image"
ItemStyle-HorizontalAlign="Center">
<ControlStyle Height="100px" Width="100px"></ControlStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:ImageField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="false"
CommandName="btnAddToCart" Text="Add To Cart" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
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
You’re defining columns in the GridView source AND by databinding a data source to the GridView. Therefore you have two sources of columns; there may or may not be a guaranteed order in which columns are added to the GridView.
Instead, why not set AutoGenerateColumns for the GridView to False and then explicitly specify the column order by using BoundField for each field you want from the data source in your GridView source followed by your image and button columns?
Method 2
I don’t know if there’s a less hacky way, but you could use RowDataBound to change the order, so that the AutoGenerated columns are followed by your other columns:
protected void gridOffers_RowDataBound(object sender, GridViewRowEventArgs e)
{
TableCell cell = e.Row.Cells[0];
e.Row.Cells.RemoveAt(0);
//Move first to the end
e.Row.Cells.Add(cell);
cell = e.Row.Cells[0];
e.Row.Cells.RemoveAt(0);
//Move second to the end
e.Row.Cells.Add(cell);
}
Method 3
Do you have AutoGenerateColumns set to true on the Gridview? If so set this to false and manually set the fields in the grid using asp:BoundField setting the DataField to the name of the field from the datasource.
This way you can set the exact order of your columns.
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