Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Place button as LAST column in gridview

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: enter image description here 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>
like image 302
David Avatar asked Jan 17 '23 01:01

David


2 Answers

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?

like image 146
kaj Avatar answered Jan 21 '23 10:01

kaj


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);
}
like image 43
Tim Schmelter Avatar answered Jan 21 '23 10:01

Tim Schmelter